我正在尝试过滤Request.Headers
返回的标题列表:
var validHeaders = (HttpRequestHeaders)Request.Headers.Where(header => ValidHeaders.List.Contains(header.Key.ToUpper()));
我收到以下异常:
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?
答案 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);
}