Search code examples
c#windows-phone-7

Setting the User-Agent header for a WebClient request


What is the proper way of setting the User-Agent header for a WebClient request for Windows Phone 7? I found 2 options, but not sure which one is the correct one. Considering a WebClient object:

WebClient client = new WebClient();

I saw 2 options:

  1. set the User-Agent using:

    client.Headers["User-Agent"] = "myUserAgentString";
    
  2. set the User-Agent using the WebHeaderCollection:

    WebHeaderCollection headers = new WebHeaderCollection();
    headers[HttpRequestHeader.UserAgent] = "userAgentString";
    client.Headers = headers;
    

Can you please advise which of the 2 methods above is the proper one?


Solution

  • You can check the WebClient documentation for a C# sample that adds a User-Agent to your WebClient and here for a sample for Windows Phone.

    This is the sample for C#:

    WebClient client = new WebClient ();
    
    // Add a user agent header in case the 
    // requested URI contains a query.
    
    client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; " + 
                                      "Windows NT 5.2; .NET CLR 1.0.3705;)");
    

    This is a sample for Windows Phone (Silverlight):

    request.Headers["UserAgent"] = "appname";
    // OR
    request.UserAgent = "appname";