Webclient doesnt like UrlEncoded slash. How to make it work?

367 Views Asked by At

I'm trying to pass an URL to an API using a .net 2.0 webclient (unable to upgrade). The webclient call only works if there are no slashes in the encoded value. Any idea why it is failing and how to make it work?

using System.Net;
using System.Text;
using System.Web;

namespace ConsoleAppWebClient
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.Accept] = "application/xml";
                var requestUrl = HttpUtility.UrlEncode("https://www.somewebsite.com");
                var stringResult = client.DownloadString("https://localhost:12345/api/getstuff/" + requestUrl);
            }
        }
    }
}

The above doesnt work but the below works just fine

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using System.Web;

namespace ConsoleAppWebClient
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.Accept] = "application/xml";
                var requestUrl = HttpUtility.UrlEncode("https:www.somewebsite.com");
                var stringResult = client.DownloadString("https://localhost:12345/api/getstuff/" + requestUrl);
            }
        }
    }
}
1

There are 1 best solutions below

5
Scott Hannen On BEST ANSWER

It looks like requestUrl is meant to be a query parameter, but you're adding it to the URL's path.

The result is

https://localhost:12345/api/getstuff/https%3A%2F%2Fwww.somewebsite.com

"%" is an unsafe character which can lead to unpredictable results.

Instead, try making it a querystring parameter:

var requestUrl = HttpUtility.UrlEncode("https:www.somewebsite.com");
var stringResult = client.DownloadString(
    "https://localhost:12345/api/getstuff/?requestUrl=" + requestUrl);

Now that the URL-encoded parameter is in the querystring instead of the path it should be okay.