开发者

Change UserAgent in Code in .NET

How can I change the HttpContext.Current.Request.UserAgent property u开发者_如何学运维sing reflection?

Thanks


I solved it by using a ashx (as a proxy) and making a request from that service to the page with a custom useragent header and then printed the answer I got from the other page.


string userAgent = "stuff";
PropertyInfo pUserAgent = HttpContext.Current.Request.GetType().GetProperty("UserAgent");
pUserAgent.SetValue(HttpContext.Current.Request, userAgent, null);

Sorry, looked up the wrong class. You can't set the property, unless you modify the private field behind it. HttpRequest.UserAgent doesn't allow setter access.


You have to use HttpWebRequest

HttpWebRequest.UserAgent Property


You can't modify the incoming request's user agent. It is the value that is sent by the users browser so I'm not sure why you would want to change it anyways. If you were creating an outbound request yourself using the HttpWebRequest class you could set its .UserAgent property, or you could add to the .Headers collection if you were using a WebClient class.


HttpContext.Current.Request is read only and so does HttpContext.Current.Request.UserAgent. This is so by nature of web, there's no reason why you may want to change anything within HttpRequest object since this has sent by some HttpClient on which you may never have control. Even in a case when you could change it, you're losing the integrity of the original Request which is obviously not recommended. I don't know what you're trying to achieve by changing the Request object or its properties, but I know for sure that's not the way to go. Try to work out some other way instead of changing the Request object, or write your actual problem statement here and we'll try to help you out.


My problem was that the page Nav_Side.aspx uses some ancient UI components which throw a 500 error unless the browser makes the request in compatibility mode.

I wanted to be able to control compatibility mode on a page-by-page basis, so used Andreas idea of using an ashx to receive the initial request, modify it and transfer to the aspx.

After creating an ashx in Visual Studio, replace the ProcessRequest method with your own code, in my case:

public void ProcessRequest(HttpContext context){
    var headers = context.Request.Headers;
    //set a User-Agent header that mimics compatibility mode for Nav_Side.aspx
    headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0)";       
    context.Server.TransferRequest("Nav_Side.aspx", true, context.Request.HttpMethod, headers);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜