如何从Request转换过滤的HttpRequestHeaders列表?

时间:2017-07-30 23:54:56

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

我正在尝试过滤Request.Headers返回的标题列表:

var validHeaders = (HttpRequestHeaders)Request.Headers.Where(header => ValidHeaders.List.Contains(header.Key.ToUpper()));

enter image description here

我收到以下异常:

  

System.InvalidCastException:'无法转换类型的对象   'WhereEnumerableIterator 1[System.Collections.Generic.KeyValuePair 2 [System.String,System.Collections.Generic.IEnumerable`1 [System.String]]]'   输入'System.Net.Http.Headers.HttpRequestHeaders'。'

如何将Request.Headers.Where表达式转换为HttpRequestHeaders?

1 个答案:

答案 0 :(得分:3)

当您应用Where子句时,它会返回IEnumerable<KeyValuePair<string, IEnumerable<string>>>的枚举,并且无法强制转换为HttpRequestHeaders类。您必须创建一个新实例,遍历已过滤的集合并将项目添加到新创建的实例。

var validHeaders = Request.Headers.Where(header => ValidHeaders.List.Contais(header.Key.ToUpper()));
//create GET request
var request = new HttpRequestMessage(HttpMethod.Get, uri);
//Add the valid headers to the new request
foreach(var header in validHeaders) {
    request.Headers.Add(header.Key, header.Value);
}