views:

1237

answers:

2

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

+4  A: 

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.

Mehrdad Afshari
+2  A: 

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.

tvanfosson
deepesh khatri