C# OWIN上的应用程序\u PreSendRequestHeaders()
我有一个不使用OWIN中间件的应用程序,它具有以下C# OWIN上的应用程序\u PreSendRequestHeaders(),c#,asp.net-mvc,owin,C#,Asp.net Mvc,Owin,我有一个不使用OWIN中间件的应用程序,它具有以下Global.asax: public class MvcApplication : HttpApplication { protected void Application_Start() { //... } protected void Application_PreSendRequestHeaders() { Response.Headers.Remov
Global.asax
:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
//...
}
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("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>();
}
}
或者您的中间件将不会在“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...
}
}
您好,您有机会尝试答案提供的解决方案吗?@LeftyX在本地环境下,它们不起作用。我还没有在生产环境中进行测试。将与您保持联系。@LeftyX您的两个答案在生产中都起了作用!我选择@peco的一个是因为我认为注册一个对
OnSendingHeaders
的回调是正确的方法。非常感谢你!很高兴我帮了点忙。干杯。这对我不起作用,HTTP响应在进入浏览器时仍然设置了标题。你能确认这对你有用吗?其他在线资源表明,标题设置的级别要低得多。如果这仅适用于由IIS托管的网站,请修改您的回复以澄清
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...
}
}