是否可以将Request.Headers与另一个列表相交?

时间:2017-07-30 03:37:46

标签: c# asp.net asp.net-web-api httprequest visual-studio-2017

我正在尝试与标题列表相交:

var validHeaders = Request.Headers.ToArray().Intersect(ValidHeaders.List);

其中ValidHeaders定义为:

public static class ValidHeaders
{
    public static readonly IList<string> List = new ReadOnlyCollection<string>
    (new List<string>
    {
        "Content-Type",
        "DataServiceVersion",
        "MinDataServiceVersion",
        "Accept",
        "If-Match",
        "If-None-Match",
        "Prefer"
    });
}

如何将HttpRequestHeaders列表与其他列表相交?

1 个答案:

答案 0 :(得分:2)

返回在Key

中找到ValidHeaders.List(标题名称)的标题的所有标题及其值
var validHeaders = Request.Headers.Where(header => ValidHeaders.List.Any(k => string.Equals(k, header.Key, StringComparison.InvariantCultureIgnoreCase)));

这可以作为扩展方法添加到静态ValidHeader

public static class ValidHeaders {
    public static readonly IList<string> List = new ReadOnlyCollection<string>(new List<string>
    {
        "Content-Type",
        "DataServiceVersion",
        "MinDataServiceVersion",
        "Accept",
        "If-Match",
        "If-None-Match",
        "Prefer"
    });

    public static IEnumerable<KeyValuePair<string, IEnumerable<string>>> GetValidHeaders(this HttpRequestMessage request) {
        var validHeaders = request.Headers.Where(header => ValidHeaders.List.Any(k => string.Equals(k, header.Key, StringComparison.InvariantCultureIgnoreCase)));
        return validHeaders;
    }
}

并使用

var validHeaders = Request.GetValidHeaders();