Search code examples
c#webclienthttp-error

Webclient 404 protocol error on valid url c#


I have a webclient that calls to a URL that works fine when i view it in a browser, which led me to believe i would need to add headers in to my call

I have done this, but am still getting the error.

I do have other calls to the same API that work fine, and have checked that all the parameters I am passing across are exactly the same as expected(case, spelling)

using (var wb = new WebClient())
{
    wb.Proxy = proxy;
    wb.Headers.Add("Accept-Language", " en-US");
    wb.Headers.Add("Accept", " text/html, application/xhtml+xml, */*");
    wb.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"); 
    byte[] response = wb.UploadValues("http://myserver/api/account/GetUser",
                                      new NameValueCollection()
                                      {
                                          { "email", register.Email },
                                      });
    userDetails = Encoding.UTF8.GetString(response);
} 

Does anyone have an idea why I am still getting the protocol error on a call that works perfectly fine in a browser?


Solution

  • UploadValue uses a HTTP POST. Are you sure that it what you want? If you are viewing it in a browser it is likely a GET, unless you are filling out some sort of web form.

    One might surmise that what you are trying to do is GET this response "http://myserver/api/account/GetUser?email=blah@blah.com"

    in which case you would just formulate that url, with query parameters, and execute a GET using one of the DownloadString overloads.

    using (var wb = new WebClient())
    {
        wb.Proxy = proxy;
        userDetails = wb.DownloadString("http://myserver/api/account/GetUser?email=" + register.Email);
    } 
    

    The Wikipedia article on REST has a nice table that outlines the semantics of each HTTP verb, which may help choosing the appropriate WebClient method to use for your use cases.