11

在 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);
    }
}

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

4

1 回答 1

10

httpContext.Request.Headers是一个Dictionary。您可以通过将标头名称作为键来返回标头的值:

context.Request.Headers["Connection"].ToString()
于 2018-03-15T21:02:45.377 回答