Application_PreSendRequestHeaders() on OWIN
本文关键字:on OWIN PreSendRequestHeaders Application | 更新日期: 2023-09-27 18:19:34
我有一个不使用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?
}
您可以创建自己的中间件并将其直接注入管道:
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<SniffMiddleware>();
}
}
不要忘记安装Microsoft.Owin.Host.SystemWeb
:
Install-Package Microsoft.Owin.Host.SystemWeb
否则您的中间件将不会在"IIS集成管道"中执行。
您可以为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...
}
}