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

enb141 picture enb141 · Nov 11, 2015 · Viewed 40.2k times · Source

Hi 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.

Answer

vcsjones picture vcsjones · Nov 11, 2015

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.