Search code examples
c#httphandlerihttphandlerhttpserverutility

Execute IHttpHandler to MemoryStream


I am wanting to use something like HttpServerUtility.Execute to execute an IHttpHandler and write the handler response to a MemoryStream that can then be parsed into an http response (functionally, I want access to the headers and the content returned).

Currently the HttpServerUtility.Execute method has a parameter for a TextWriter object (can be a StringWriter object) but this only caters for requests that return a text/string body, also I cannot read the content-type header of the response (say for a text/css response). If say I had a handler that I wanted to execute that outputs an image the StringWriter would not work as this deals with binary data.

Basically I want to execute one IHttpHandler (could be a System.Web.UI.Page) inside another IHttpHandler and store the response in a MemoryStream.

Any assistance with this would be appreciated.

Thanks.


Solution

  • Maybe you can invoke the ProcessRequest method on the IHttpHandler object directly and pass it your own http context with your own response object. I'm not sure but I think the BinaryWrite method of the http response uses the output stream of the TextWriter object that is passed into it's constructor. So if you have a memory stream set in the TextWriter then you could use it as your output.

    So:

    • Create MemoryStream
    • Create StreamWriter and pass memory stream into the constructor
    • Create a HttpResponse and pass it the created StreamWriter
    • Create an HttpContext with the created HttpResponse and a created or current http request
    • Invoke IHttpHandler.ProcessRequest