OWIN上的Application_PreSendRequestHeaders()
我有一个不使用OWIN中间件的应用程序,并具有以下Global.asax
:
public class MvcApplication : HttpApplication { protected void Application_Start() { //... } protected void Application_PreSendRequestHeaders() { Response.Headers.Remove("Server"); } }
每次应用程序发送响应时,都会删除Server
标头。
如何使用使用OWIN的应用程序执行相同操作?
public class Startup { public void Configuration(IAppBuilder application) { //... } //What method do I need to create here? }
您可以为IOwinResponse.OnSendingHeaders
事件注册回调:
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... } }
您可以创建自己的中间件并将其直接注入管道:
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(); }); } }
或自定义中间件:
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); } }
你可以这样注入管道:
public class Startup { public void Configuration(IAppBuilder app) { app.Use(); } }
不要忘记安装Microsoft.Owin.Host.SystemWeb
:
Install-Package Microsoft.Owin.Host.SystemWeb
或者您的中间件不会在“IIS集成管道”中执行。