【发布时间】:2018-08-24 18:06:34
【问题描述】:
在 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);
}
}
我的目标是提取所有请求标头,而不仅仅是一些我必须知道特定键的选定标头。
【问题讨论】:
-
IHeaderDictionary 实现了 IDictionary,你应该可以使用所有普通的 IDictionary API。
-
var contentType = headers["Content-Type"]; -
感谢大家的投入,我能够得到我想要的。为了获得我需要创建一个以 IHeaderDictionary 作为输入的新 Dictionary
所需的所有标题,就像这样: var headerDictionary = new Dictionary<string, StringValues>(headers) -
@philipp-fx - 你应该在这里回答你自己的问题并接受答案。这个技巧真的很有用,而且绝对不是另一个问题的重复 :( - 很遗憾答案在 cmets 中很混乱。
标签: c# asp.net-core asp.net-core-2.0 asp.net-core-middleware request-pipeline