Is there a way to test WebResponse without affecting the main response flow in .NET?

After calling the initial HttpWebResponse.GetResponseStream () and reading through the stream, this stream is executed and cannot be reused.

I have a situation where I need to examine the contents of a response and, if it has certain data, get another page, and then pass a new answer along the line. Otherwise, pass the original answer as is. The only problem is that after checking the response to check this "special data" this answer is not suitable for the code downstream.

The only way I can make it transparent to the downstream code is to create a HttpWebResponse derived class and somehow cache the data streams and pass that cached stream down the line instead of the initial stream, I'm not sure if this is possible even after that as I have not studied it.

Are there any alternative ways to handle this scenario?

+4
source share
3 answers

How about this:

using (var client = new WebClient()) { string result = client.DownloadString("http://www.foo.bar"); // TODO: examine result as much as you wish } 

If you do not want to load the entire answer into memory, you can pass it to some parsing function, which will check it once and return an object containing all the properties you are interested in, so that after you can examine this object as you wish.

+4
source

Have you tried to set the stream position back to 0 ?

After processing the stream, the cursor is at the end of the stream. Therefore, when ASP.NET begins to process the stream, there is nothing to read. Try moving the cursor to the beginning of the stream - then ASP.NET can read the entire request.

+2
source

Looks like this might be the right place for a message inspector . You must rewrite AfterReceiveRequest to find the corresponding "specific data". If no β€œcertain data” then returned a copy to the message body and disappeared, otherwise you may need to raise an event or throw an exception that your code will catch, and then β€œgo to another page”.

With the help of the message inspector, you can view the incoming / outgoing data, change it if you want, or transfer it unchanged to the original destination.

Note. For message controllers and user actions, you will need .NET 3.0 or higher.

+1
source

All Articles