Change the Uri of a instance of HttpWebRequest?

2019-06-23 02:00发布

问题:

I have an instance of an HttpWebRequest that I'm intercepting in an event. I would like to edit the url before the request is sent but I can't find a way of doing this. The property RequestUri is read only.

I've thought of a few ways but can't seem to find a working solution: -Using reflection to set the value ? -Creating a new request and then cloning all properties. not sure how to do that.

回答1:

If you think in terms of the HTTP protocol, each request is stateless / unique. The only way to link one request to another is programmatically through something like Cookies, but to the HTTP protocol itself the request is unique.

I think the HttpWebRequest object was designed with this in mind. Each HttpWebRequest represents one unique call to a URL and you build up the parameters for that call. If you want to do another request to a different URL you would create a new HttpWebRequest and pass it the state information you are using, ie: Cookie container, header information etc.

The long winded answer to this is the object is designed to have a read only url and the only way to handle it is to:

  1. Use a little reflection hack, such as you have already done, if you absolutely need to use the given HttpWebRequest object you have.

  2. Create a new HttpWebRequest (WebRequest.Create()) and copy your state information over to the new request.



回答2:

You can use RewritePath to do this.

F.e.

HttpContext.Current.RewritePath("newurl.aspx");