简体   繁体   中英

How to access response body in ASP.NET

I can add headers via:

Response.Headers.Add("Key", "Value");

and then access the value in the header through:

var header = Response.Headers["Key"];

I was wondering if there was any way to access the body of a response in a similar way. ie when I write Response.Write("Hello World"); I want to be able to get that 'Hello World'. there's a Response.Output._charBuffer which kinda does the job but then again it's accessible Privately.

Update: I just want to check if the response body is empty or not. I don't actually need the body itself.

Is your goal to store and read only strings from the Response object? If so you can do something like this

  using (StreamReader sr = new StreamReader(HttpContext.Response.Body))
  {
      var stringResult = sr.ReadToEnd(); //This should be equal to "Hello World"
  } 

Update : I red your comment that you are working on .NET 4.5. Try this then:

 using (StreamReader sr = new StreamReader(HttpContext.Response.OutputStream))
 {
      var result = sr.ReadToEnd();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM