c# - ASP.Net Core 2.0 如何获取中间件中的所有请求头?

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

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

问题是我不知道如何提取所有键值对 header 。我需要的 header 存储在 protected 属性中

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

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

最佳答案

httpContext.Request.Headers 是一个字典。您可以通过将 header 名称作为键传递来返回 header 的值:

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

关于c# - ASP.Net Core 2.0 如何获取中间件中的所有请求头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49307762/

相关文章:

c# - 如何以编程方式删除 Outlook 2013 中的菜单上下文项

c# - 使用 Microsoft.Identity 与 Azure.Identity 对 Microsoft Graph 的守护进程调用

asp.net - 从ASP.NET Core 2.0 API中的JWT token 获取声明

asp.net-core - 无法加载 csproj 的项目文件

asp.net - asp.net core 2.0 中的机器 key ?

c# - 创建分组中继器布局

c# - ASP.NET 当单选按钮列表中选定的索引发生变化时如何调用我的函数而不更新整个页面?

c# - Entity Framework 不可为空的列映射到可为空的实体属性

c# - 在ABP中从CrudAppService检索子实体

asp.net - 表单键或值长度限制 2048 超出