Application_PreSendRequestHeaders() 在 OWIN 上

Application_PreSendRequestHeaders() on OWIN

我有一个不使用 OWIN 中间件的应用程序,它具有以下 Global.asax

public class MvcApplication : HttpApplication
{
     protected void Application_Start()
     {
         //...
     }

     protected void Application_PreSendRequestHeaders()
     {
         Response.Headers.Remove("Server");
     }
}

这会在每次应用程序发送响应时删除 Server header。

如何对使用 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 integrated pipeline".

中执行

您可以为 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...
    }
}