How to modify request headers in c#,ASP .NET

戏子无情 提交于 2019-12-10 11:29:39

问题


I am working on a ASP .NET mVC project & i have to change HttpHeaders. see the foolowing code snippet:

WebRequest req= HttpWebRequest.Create("myURL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

req.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.15) Gecko/2009101601 Firefox/3.0.15 (.NET CLR 3.5.30729)");
req.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
req.Headers.Add("Accept-Language", "en-us,en;q=0.5");

this gives a exception i.e.

This header must be modified using the appropriate property.\r\nParameter name: name.

Anyone suggets solution for it


回答1:


In addition to what @Mehrdad Afshari says, your req variable needs to be of type HttpWebRequest. WebRequest (the abstract parent class) doesn't have the UserAgent and Accept properties.

HttpWebRequest req = WebRequest.Create( "http://..." ) as HttpWebRequest;

Also, I just want to make sure that you are really trying to change the headers on a request that you are sending from your MVC application, not on the response that is being sent back from your MVC application. The way you've written the code is a little confusing as you are setting the headers after receiving the response, which won't work, and because you specifically refer to MVC. If you are creating a WebRequest on the server it really doesn't matter whether you are using WebForms or MVC, the process is still the same.

If it turns out that you are trying to change the format of the response you are sending back, leave a comment and let me know.




回答2:


You should set header values that have a corresponding property in the object through the property. For instance, UserAgent property is provided to set the user agent. You should modify the header with:

req.UserAgent = "Mozilla/5.0 ...";

Of course, you should set header values before calling GetResponse.



来源:https://stackoverflow.com/questions/1812411/how-to-modify-request-headers-in-c-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!