15

I'm trying to set User Agent with WebRequest, but unfortunately, I've only found how to do it using HttpWebRequest, so here is my code and I hope you can help me to set the User-Agent using WebRequest.

here is my code

    public string Post(string url, string Post, string Header, string Value)
    {
        string str_ReturnValue = "";

        WebRequest request = WebRequest.Create(url);

        request.Method = "POST";
        request.ContentType = "application/json;charset=UTF-8";                        
        request.Timeout = 1000000;

        if (Header != null & Value != null)
        {
            request.Headers.Add(Header, Value);                                
        }

        using (Stream s = request.GetRequestStream())
        {
            using (StreamWriter sw = new StreamWriter(s))
                sw.Write(Post);
        }

        using (Stream s = request.GetResponse().GetResponseStream())
        {                
            using (StreamReader sr = new StreamReader(s))
            {
                var jsonData = sr.ReadToEnd();
                str_ReturnValue += jsonData.ToString();
            }
        }

        return str_ReturnValue;
    }

I have tried with adding request.Headers.Add("user-agent", _USER_AGENT); but I receive an error message.

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
enb141
  • 156
  • 1
  • 1
  • 10

3 Answers3

39

Use the UserAgent property on HttpWebRequest by casting it to a HttpWebRequest.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "my user agent";

Alternatively, instead of casting you can use WebRequest.CreateHttp instead.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • The problem is that I can't use HttpWebRequest, because the Post I'm doing doesn't works, I've made it working using WebRequest. – enb141 Nov 11 '15 at 21:07
  • 1
    @user1102989 you *are* using an `HttpWebRequest` - it's a super type of `WebRequest`. All you are doing with the cast is making the type more specific. – vcsjones Nov 11 '15 at 21:09
  • 1
    @user1102989 `User Agent` is a field in HTTP headers - meaning, it's specific to HTTP protocol. Hence, it makes sense there is no functionality to set it directly on `WebRequest` class, because this class is designed to be the base class for requests made using any kind of protocol. – kamilk Nov 11 '15 at 22:30
  • Thanks after using HttpWebRequest I was able to set my UserAgent. – enb141 Nov 12 '15 at 19:59
  • (much later comment). You can also cast just the property if the instance already exists as a WebRequest; I bumped into this not wanting to touch existing legacy code. `WebRequest request = WebRequest.Create(url); ((HttpWebRequest)request).UserAgent = "my user agent";` – goodeye Mar 11 '17 at 21:09
  • Instead of setting a hard coded value, I want to get a valid User Agent value from client at runtime and set it to UserAgent property. Can anyone please suggest a way to do that? – Ashu Nov 24 '21 at 06:12
2

If you try using a HttpWebRequest instead of a basic WebRequest, then there is a specific property exposed for UserAgent.

// Create a new 'HttpWebRequest' object to the mentioned URL.
var myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.UserAgent=".NET Framework Test Client";

// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
var myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
Reddog
  • 15,219
  • 3
  • 51
  • 63
  • 2
    So there's no way about adding UserAgent using WebRequest? – enb141 Nov 11 '15 at 21:11
  • 1
    I think that UserAgent would be specific to HTTP web requests. Which is why it's not on the base class `WebRequest`. If you are using `WebRequest.Create` this factory function is creating `HttpWebRequest` objects anyway (as per the example code above) so you should be safe to cast and use the `UserAgent` property there. – Reddog Nov 11 '15 at 23:17
  • Thanks with HttpWebRequest I was able to set my custom User Agent – enb141 Nov 12 '15 at 20:00
-1
WebRequest postrequest = WebRequest.Create("protocol://endpointurl.ext");
((System.Net.HttpWebRequest)postrequest).UserAgent = ".NET Framework"
Audreth
  • 67
  • 5