如何使用中间件删除服务器头?

时间:2016-07-09 08:37:18

标签: asp.net-core .net-core asp.net-core-1.0 asp.net-core-middleware

在ASP.NET Core 1.0中,每个响应都包含标题Server: Kestrel。我想使用中间件删除此标头以及其他标头,如X-Power-By

我知道我们可以通过设置以下内容来删除主机配置中的Kestrel标头但是我想使用中间件来实现(实际上当我们有Httpmodule时我们可以这样做,所以我学习同样的事情)。我试了一下它没用。

new WebHostBuilder()
    .UseKestrel(c => c.AddServerHeader = false)

尝试过的代码:

public class HeaderRemoverMiddleware
{
    private readonly RequestDelegate _next;
    public HeaderRemoverMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        httpContext.Response.OnStarting(callback: removeHeaders, state: httpContext);
        await _next.Invoke(httpContext);
    }

    private Task removeHeaders(object context)
    {
        var httpContext = (HttpContext)context;
        if (httpContext.Response.Headers.ContainsKey("Server"))
        {
            httpContext.Response.Headers.Remove("Server");
        }
        return Task.FromResult(0);
    }
}

public static class HeaderRemoverExtensions
{
    public static IApplicationBuilder UseServerHeaderRemover(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<HeaderRemoverMiddleware>();
    }
}

1 个答案:

答案 0 :(得分:17)

我已经验证此代码在Kestrel 1.0.0中正常运行:

.UseKestrel(opt => opt.AddServerHeader = false)

这会从响应中删除Server: Kestrel标头。

如果要从响应中删除其他任意标头,则代码的变体将起作用。 适用于Server: Kestrel标头,因为看起来Kestrel在OnSending委托运行后添加此内容。

这是一个示例中间件,它会删除您传递给它的所有标头:

public class HeaderRemoverMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ImmutableList<string> _headersToRemove;

    public HeaderRemoverMiddleware(RequestDelegate next, ImmutableList<string> headersToRemove)
    {
        _next = next;
        _headersToRemove = headersToRemove;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        httpContext.Response.OnStarting(() =>
        {
            _headersToRemove.ForEach(header =>
            {
                if (httpContext.Response.Headers.ContainsKey(header))
                {
                    httpContext.Response.Headers.Remove(header);
                }
            });

            return Task.FromResult(0);
        });

        await _next.Invoke(httpContext);
    }
}

public static class HeaderRemoverExtensions
{
    public static IApplicationBuilder UseHeaderRemover(this IApplicationBuilder builder, params string[] headersToRemove)
    {
        return builder.UseMiddleware<HeaderRemoverMiddleware>(headersToRemove.ToImmutableList());
    }
}

要使用它,请将其添加到应用程序管道的最顶层:

app.UseHeaderRemover("Content-Type", "AnotherHeader");