enb141
enb141

Reputation: 186

How to set User Agent with System.Net.WebRequest in c#

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.

Upvotes: 18

Views: 59413

Answers (3)

Audreth
Audreth

Reputation: 67

WebRequest postrequest = WebRequest.Create("protocol://endpointurl.ext");
((System.Net.HttpWebRequest)postrequest).UserAgent = ".NET Framework"

Upvotes: -1

Reddog
Reddog

Reputation: 15579

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();

Upvotes: 2

vcsjones
vcsjones

Reputation: 141678

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.

Upvotes: 43

Related Questions