ASP.Net Core 2.0如何在中间件中获取所有请求标头?

时间:2018-03-15 19:28:10

标签: c# asp.net-core asp.net-core-2.0 asp.net-core-middleware request-pipeline

在ASP.Net Core 2.0中,我试图验证自定义中间件中的传入请求标头。

问题在于我不知道如何提取所有键值对标头。我需要的标题存储在受保护的属性

protected Dictionary<string, stringValues> MaybeUnknown

到目前为止,我的中间件类看起来像这样:

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

    public async Task Invoke(HttpContext httpContext)
    {
        IHeaderDictionary headers = httpContext.Request.Headers; // at runtime headers are of type FrameRequestHeaders

        // How to get the key-value-pair headers?
        // "protected Dictionary<string, stringValues> MaybeUnknown" from headers is inaccessbile due to its protection level
        // Casting headers as Dictionary<string, StringValues> results in null

        await _next.Invoke(httpContext);
    }
}

我的目标是提取所有请求标头,而不仅仅是一些我必须知道特定密钥的选定标头。

1 个答案:

答案 0 :(得分:4)

httpContext.Request.HeadersDictionary。您可以通过将标题名称作为键来返回标题的值:

context.Request.Headers["Connection"].ToString()