'OWIN middleware does not get invoked for all requests
I am trying to add content security policy header in response header for all requests. So I have created OWIN middleware
public class SecurityHeaderMiddleware
{
private readonly INonceService _nonceService = null;
private readonly Func<Task> _next;
public SecurityHeaderMiddleware(Func<Task> next, INonceService nonceService)
{
_nonceService = nonceService;
_next = next;
}
public async Task Invoke(IOwinContext context)
{
// do something here to add CSP header in context.Response.Headers
await _next.Invoke();
}
Then to invoke my middleware for each request, I register my middleware in startup.cs before PostResolveCache stage marker as per the suggestion here
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use((context, next) =>
{
var nonceService = ServiceLocator.Current.GetInstance<INonceService>();
var middleware = new SecurityHeaderMiddleware(next, nonceService);
return middleware.Invoke(context);
});
app.UseStageMarker(PipelineStage.PostResolveCache);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// set options here
});
MvcHandler.DisableMvcResponseHeader = true;
}
}
However, my middleware only gets invoked for actual page or any ajax request, it does not get invoked when browser make request to javascript, CSS or images
How do I invoke custom middleware for all requests? If not OWIN middleware then what are my options to add header for all requests in asp.net
Solution 1:[1]
I've noticed that owin middleware is only invoked for requests which are serviced by MVC handler.
Answer was to add catch all routing, so everything is routed to mvc handler.
Solution 2:[2]
I guess the PostAuthorize stage marker should be set to handle static content requests. It's even mentioned in the linked issue's comments:
app.Use(...);
app.UseStageMarker(PipelineStage.PostAuthorize);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shadow |
| Solution 2 |
