在花了一些时间寻找开箱即用的解决方案后,我结束了对System.Net.WebHeaderCollection 的扩展方法:
public static class WebHeaderCollectionExtensions
{
public static ILookup<string, string> ToLookup(this WebHeaderCollection some)
{
List<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>();
if (some.Count > 0)
{
string[] tempSplittedHeaders = null;
foreach (string headerName in some)
{
if (some[headerName].Contains(";,"))
{
tempSplittedHeaders = Regex.Split(some[headerName], ";,");
foreach (string splittedHeader in tempSplittedHeaders)
{
headers.Add(new KeyValuePair<string, string>(headerName, splittedHeader));
}
}
else
{
headers.Add(new KeyValuePair<string, string>(headerName, some[headerName]));
}
}
}
return headers.ToLookup(keySelector => keySelector.Key, elementSelector => elementSelector.Value);
}
}
感谢这个奇妙的扩展方法,我能够将标头的集合转换为允许重复键的查找,并且在一天结束时,进行一些处理,我分别获得了所有 HTTP 标头的列表:
string wholeCookie = WebOperationContext.Current.IncomingRequest.Headers.ToLookup()["Set-Cookie"].Single(cookie => cookie.Contains("[Cookie name]"));
我希望分享我的解决方案将是一个很好的贡献,因为我猜其他人已经或正在使用类似的案例!