3

According to this information given by the Asp.Net team What not to do in Asp.net you should not use PreSendRequestHeaders in a managed HttpModule.

PreSendRequestHeaders and PreSendRequestContext

Recommendation: Do not use these events with managed modules.

The PreSendRequestHeaders and PreSendRequestContext events can be used with native IIS modules, but not with managed modules that implement IHttpModule. Setting these properties can cause issues with asynchronous requests.

This is precisely what I do in my Image Processing Library to ensure that the correct mime type is sent along with the response.

What would be the recommended alternative approach?

dunc
  • 81
  • 2
  • 7
James South
  • 10,147
  • 4
  • 59
  • 115
  • https://github.com/JimBobSquarePants/ImageProcessor/blob/master/src/ImageProcessor.Web/NET45/HttpModules/ImageProcessingModule.cs#L143 not found – Kiquenet Apr 17 '19 at 09:38
  • Should have used the absolute link. Code is long gone now using `PostReleaseRequestState` instead. https://github.com/JimBobSquarePants/ImageProcessor/blob/c36a37d250432a6e93bc4b1a04410ddc2e193c02/src/ImageProcessor.Web/HttpModules/ImageProcessingModule.cs#L328 – James South Apr 22 '19 at 11:48

2 Answers2

5

In a handler for BeginRequest, use HttpResponse.AddOnSendingHeaders to subscribe a handler for that event.

This is essentially the same thing as PreSendRequestHeaders, however it is handled fully within the ASP.NET pipeline so it doesn't have the same problems with the native/managed interface that PreSendRequestHeaders does.

chkimes
  • 1,127
  • 13
  • 20
1

If you look at the HttpApplication pipeline on MSDN's ASP.NET App Life Cycle page you'll find PreSendRequestHeaders and PreSendRequestContent events at the very bottom. Now that they're suggesting we not use these in managed IHttpModules, the next closest event in the pipeline would be EndRequest, which is deterministic unlike PreSendRequest* events.

I haven't been able to find any information on what the preferred practice is now for specifying response headers, but this will work for you.

mikesjawnbit
  • 106
  • 6
  • 1
    Too bad, this won't work. `EndRequest` is too late, it will result in an exception. See http://stackoverflow.com/questions/7198205/exception-thrown-in-end-request-when-adding-headers – Julian Sep 13 '14 at 18:43