问题
I have an application that does not use OWIN middleware and has the following Global.asax
:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
//...
}
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
}
}
This removes the Server
header each time the application sends a response.
How can I do the same with an application that uses OWIN?
public class Startup
{
public void Configuration(IAppBuilder application)
{
//...
}
//What method do I need to create here?
}
回答1:
You could register a callback for the IOwinResponse.OnSendingHeaders
event:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use(async (context, next) =>
{
context.Response.OnSendingHeaders(state =>
{
((OwinResponse)state).Headers.Remove("Server");
}, context.Response);
await next();
});
// Configure the rest of your application...
}
}
回答2:
You can create your own piece of middleware and inject it directly into the pipeline:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use(async (context, next) =>
{
string[] headersToRemove = { "Server" };
foreach (var header in headersToRemove)
{
if (context.Response.Headers.ContainsKey(header))
{
context.Response.Headers.Remove(header);
}
}
await next();
});
}
}
or a custom middleware:
using Microsoft.Owin;
using System.Threading.Tasks;
public class SniffMiddleware : OwinMiddleware
{
public SniffMiddleware(OwinMiddleware next): base(next)
{
}
public async override Task Invoke(IOwinContext context)
{
string[] headersToRemove = { "Server" };
foreach (var header in headersToRemove)
{
if (context.Response.Headers.ContainsKey(header))
{
context.Response.Headers.Remove(header);
}
}
await Next.Invoke(context);
}
}
which you can inject into the pipeline this way:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use<SniffMiddleware>();
}
}
Don't forget to install Microsoft.Owin.Host.SystemWeb
:
Install-Package Microsoft.Owin.Host.SystemWeb
or your middleware won't be executed in the "IIS integrated pipeline".
来源:https://stackoverflow.com/questions/33376907/application-presendrequestheaders-on-owin