相关疑难解决方法(0)

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

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

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

new WebHostBuilder()
    .UseKestrel(c => c.AddServerHeader = false)
Run Code Online (Sandbox Code Playgroud)

试过的代码:

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>();
    }
}
Run Code Online (Sandbox Code Playgroud)

.net-core asp.net-core asp.net-core-1.0 asp.net-core-middleware

14
推荐指数
1
解决办法
5126
查看次数