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

phi*_*-fx 3 c# request-pipeline asp.net-core asp.net-core-middleware asp.net-core-2.0

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

问题是我不怎么提取所有键值对标头。我需要的标头存储在受保护的属性中

protected Dictionary<string, stringValues> MaybeUnknown
Run Code Online (Sandbox Code Playgroud)

到目前为止,我的中间件类如下所示:

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

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

Mar*_*eur 5

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

context.Request.Headers["Connection"].ToString()
Run Code Online (Sandbox Code Playgroud)

  • 通过创建一个以 `headers` 变量作为输入的新字典,我能够得到我想要的东西。谢谢! (2认同)