0

good morning, I need your help.

I have an error with WebHeaderCollection class when trying to add the header "User-Agent"   jumping me the error in visual studio is as follows:

"This header must be modified With The right property

My code is as follows and the fault is on the third line.

private static readonly WebHeaderCollection Headers = new WebHeaderCollection()
    {
        {"User-Agent", "Custom-User-Agent"}, // <<=== ERROR??
        {"Cookie", "MyCookie"},
        {"application", "netconnect"}
    };

private static void Start(int nRequests)
{
    WebRequest.DefaultWebProxy = null;

    for (var i = 0; i < nRequests; ++i) {
        SendRequest();
    }
}

private static bool SendRequest()
{
    var request = HttpWebRequest.Create("URL");
    request.Headers = Headers;


    using (var response = (HttpWebResponse)request.GetResponse()) {
        //Returns boolean indicating success
        return response.StatusCode == HttpStatusCode.OK;
    }
}

Any solution to solve this? Thank you very much!

  • possible duplicate of [Cannot set some HTTP headers when using System.Net.WebRequest](http://stackoverflow.com/questions/239725/cannot-set-some-http-headers-when-using-system-net-webrequest) – CodingGorilla Apr 25 '15 at 16:18
  • 1
    Set the [HttpWebRequest.UserAgent](https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.useragent(v=vs.110).aspx) property instead of the passing the user agent in the Headers collection. – Michael Liu Apr 25 '15 at 16:26

2 Answers2

1

As MSDN said:

Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.

You may specify UA on HttpWebRequest:

request.UserAgent = "Custom-User-Agent"
Steve.NayLinAung
  • 5,086
  • 2
  • 25
  • 49
Alan haha
  • 491
  • 1
  • 4
  • 10
0

The following can be done:

                       new HttpResponse()
                       {
                           RequestUri = string.Empty,
                           StatusCode = HttpStatusCode.OK,

                           Cookies = new CookieCollection()
                           {
                               new Cookie("MyCookie", cookie)
                           },

                           Headers = new WebHeaderCollection()
                           {
                               "X-Powered-By:Servlet/3.1 JSP/2.3 (Payara Server  4.1.1.162 #badassfish Java/Oracle Corporation/1.8)"
                           }
                       }
Mohammad Almasi
  • 400
  • 6
  • 19