如何在 C# 中使用 System.Net.WebRequest 设置用户代理

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

我正在尝试使用 WebRequest 设置用户代理,但不幸的是,我只找到了使用 HttpWebRequest 的方法,所以这是我的代码,我希望你能帮助我设置用户代理使用WebRequest.

这是我的代码

    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;
    }

我尝试添加 request.Headers.Add("user-agent", _USER_AGENT); 但我收到一条错误消息。

HttpWebRequest 上使用 UserAgent 属性,方法是将其转换为 HttpWebRequest

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

或者,您可以使用 WebRequest.CreateHttp 代替转换。

如果您尝试使用 HttpWebRequest 而不是基本的 WebRequest,则会出现 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();
WebRequest postrequest = WebRequest.Create("protocol://endpointurl.ext");
((System.Net.HttpWebRequest)postrequest).UserAgent = ".NET Framework"