17

在 ASP.NET Core 1.0 中,每个响应都将包含 header 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>();
    }
}
4

1 回答 1

26

我已经验证此代码从 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");
于 2016-07-12T15:48:02.257 回答