Writing System.Web.HttpContext.Current.Response to Text File

Julio Bello 221 Reputation points
2021-12-19T00:14:26.59+00:00

Hi, Everybody!...

I have a System.Web.HttpContext.Current.Response. All I want to do is to output its content to a file. I have made so many attempt on my own with NO success. I have scoured The Internet for an answer. Yet I found nothing. My "best" attempt was the following (no compile time errors)...

var currentResponse = System.Web.HttpContext.Current.Response;
var outputStream = currentResponse.OutputStream;

using (var output = File.OpenWrite(filePath))
using (var input = outputStream)
{
    input.CopyTo(output);
}

However, at run time, I get the following error:

System.NotSupportedException
HResult=0x80131515
Message=Stream does not support reading.
Source=mscorlib
StackTrace:
at System.IO.Stream.CopyTo(Stream destination)
at JerseyPostService.JerseyPostService.SaveResponse() in C:\Users\Julio.Bello\source\repos\TMGServices\JerseyPostService\App_Code\Service\JerseyPostService.cs:line 1164
at JerseyPostService.JerseyPostService.CreateShipment(ExtendedProperties createShipmentParameters) in C:\Users\Julio.Bello\source\repos\TMGServices\JerseyPostService\App_Code\Service\JerseyPostService.cs:line 186

>

This exception was originally thrown at this call stack:
[External Code]
JerseyPostService.JerseyPostService.SaveResponse() in JerseyPostService.cs
JerseyPostService.JerseyPostService.CreateShipment(Common.ExtendedProperties) in JerseyPostService.cs

How unusual is my request?... Certainly, there MUST be a way... Isn't there?

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,926 Reputation points Volunteer Moderator
    2021-12-19T18:02:13.51+00:00

    The default output stream is not readable. You need to to capture the bytes before they are written to the output stream.

    For asp.net core you use middleware and wrap the response stream. Example

    https://exceptionnotfound.net/using-middleware-to-log-requests-and-responses-in-asp-net-core/

    For classic asp.net you use the response filter stream

    https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponse.filter?view=netframework-4.8

    Tutorial
    https://weblog.west-wind.com/posts/2009/nov/13/capturing-and-transforming-aspnet-output-with-responsefilter


  2. SurferOnWww 4,711 Reputation points
    2022-04-17T07:47:42.713+00:00

    If you are talking about the response contents of .NET Framework ASP.NET Web Forms app (not Core) can the following thread of stackoverflow help?

    Logging raw HTTP request/response in ASP.NET MVC & IIS7
    https://stackoverflow.com/questions/1038466/logging-raw-http-request-response-in-asp-net-mvc-iis7

    Below is the HTTP module I have used to obtain the response contents for my application:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.IO;
     
    // HTTP Module
    public class ResponseContentLogHttpModule : IHttpModule
    {
      public ResponseContentLogHttpModule()
      {
      }
     
      public String ModuleName
      {
        get { return "ResponseContentLogHttpModule"; }
      }
     
      public void Init(HttpApplication application)
      {
        application.BeginRequest += this.BeginRequest;
        application.EndRequest += this.EndRequest;
      }
     
      private void BeginRequest(Object source, EventArgs e)
      {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        string filePath = context.Request.FilePath;
        string fileExtension =
            VirtualPathUtility.GetExtension(filePath);
     
        // .aspx only
        if (fileExtension.Equals(".aspx"))
        {
          HttpResponse response = context.Response;
          var filter = new OutputFilterStream(response.Filter);
          response.Filter = filter;
     
          // to use OutputFilterStream object at EndRequest
          // set its reference to HttpContext.Items.
          context.Items["FilterStream"] = filter;
        }
      }
     
      private void EndRequest(Object source, EventArgs e)
      {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        string filePath = context.Request.FilePath;
        string fileExtension = VirtualPathUtility.GetExtension(filePath);
     
        // .aspx only
        if (fileExtension.Equals(".aspx"))
        {
          // get OutputFilterStream object stored at BegineRequest above
          var filter = (OutputFilterStream)context.Items["FilterStream"];
     
          // get response content
          string responseContent = filter.ReadStream();
        }
      }
     
      public void Dispose() { }
    }
     
    // Wrapping filter class
    // (copied from stackoverflow)
    public class OutputFilterStream : Stream
    {
      private readonly Stream InnerStream;
      private readonly MemoryStream CopyStream;
     
      public OutputFilterStream(Stream inner)
      {
        this.InnerStream = inner;
        this.CopyStream = new MemoryStream();
      }
     
      public string ReadStream()
      {
        lock (this.InnerStream)
        {
          if (this.CopyStream.Length <= 0L ||
              !this.CopyStream.CanRead ||
              !this.CopyStream.CanSeek)
          {
            return String.Empty;
          }
     
          long pos = this.CopyStream.Position;
          this.CopyStream.Position = 0L;
          try
          {
            return new StreamReader(this.CopyStream).ReadToEnd();
          }
          finally
          {
            try
            {
              this.CopyStream.Position = pos;
            }
            catch { }
          }
        }
      }
     
      public override bool CanRead
      {
        get { return this.InnerStream.CanRead; }
      }
     
      public override bool CanSeek
      {
        get { return this.InnerStream.CanSeek; }
      }
     
      public override bool CanWrite
      {
        get { return this.InnerStream.CanWrite; }
      }
     
      public override void Flush()
      {
        this.InnerStream.Flush();
      }
     
      public override long Length
      {
        get { return this.InnerStream.Length; }
      }
     
      public override long Position
      {
        get { return this.InnerStream.Position; }
        set
        {
          this.CopyStream.Position =
          this.InnerStream.Position = value;
        }
      }
     
      public override int Read(byte[] buffer,
                              int offset, int count)
      {
        return this.InnerStream.Read(buffer, offset, count);
      }
     
      public override long Seek(long offset, SeekOrigin origin)
      {
        this.CopyStream.Seek(offset, origin);
        return this.InnerStream.Seek(offset, origin);
      }
     
      public override void SetLength(long value)
      {
        this.CopyStream.SetLength(value);
        this.InnerStream.SetLength(value);
      }
     
      public override void Write(byte[] buffer,
                                 int offset, int count)
      {
        this.CopyStream.Write(buffer, offset, count);
        this.InnerStream.Write(buffer, offset, count);
      }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.