Application_PreSendRequestHeaders() on OWIN

Deadly 提交于 2019-12-30 05:06:06

问题


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.OnSendingHeadersevent:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!