Application_PreSendRequestHeaders () in OWIN

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 header Serverevery time the application sends a response.

How can I do the same with an application using OWIN?

public class Startup
{
     public void Configuration(IAppBuilder application)
     {
          //...
     }

     //What method do I need to create here?
}
+4
source share
2 answers

You can register a callback for an event 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...
    }
}
+2
source

You can create your own piece of middleware and enter 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 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 enter into the pipeline this way:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use<SniffMiddleware>();
    }
}

Microsoft.Owin.Host.SystemWeb:

Install-Package Microsoft.Owin.Host.SystemWeb

" IIS".

+2

Source: https://habr.com/ru/post/1613402/