下面是@Roman修改爲一個擴展方法有少LINQ和更準確的另一個版本,而無需使用StartsWith
如果2個或更多的cookie都具有相同的名稱
public static string GetCookieValue(this HttpRequestHeaders requestHeaders, string cookieName)
{
foreach (var header in requestHeaders)
{
if (header.Key.Equals("Cookie", StringComparison.InvariantCultureIgnoreCase) == false)
continue;
var cookiesHeaderValue = header.Value.FirstOrDefault();
if (cookiesHeaderValue == null)
return null;
var cookieCollection = cookiesHeaderValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var cookieNameValue in cookieCollection)
{
var parts = cookieNameValue.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2) continue;
if (parts[0].Trim().Equals(cookieName, StringComparison.InvariantCultureIgnoreCase))
return parts[1].Trim();
}
}
return null;
}
前綴,這可能會導致錯誤的結果
部分單元測試(nunit):
[TestCase("hello=world;cookies=are fun;", "hello", "world", true)]
[TestCase("HELlo=world;cookies=are fun", "hello", "world", true)]
[TestCase("HELlo= world;cookies=are fun", "hello", "world", true)]
[TestCase("HELlo =world;cookies=are fun", "hello", "world", true)]
[TestCase("hello = world;cookies=are fun;", "hello", "world", true)]
[TestCase("hellos=world;cookies=are fun", "hello", "world", false)]
[TestCase("hello=world;cookies?=are fun?", "hello", "world", true)]
[TestCase("hel?lo=world;cookies=are fun?", "hel?lo", "world", true)]
public void Get_Cookie_Value_From_HttpRequestHeaders(string cookieHeaderVal, string cookieName, string cookieVal, bool matches)
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://test.com");
var requestHeaders = request.Headers;
requestHeaders.Add("Cookie", cookieHeaderVal);
var valueFromHeader = requestHeaders.GetCookieValue(cookieName);
if (matches)
{
Assert.IsNotNull(valueFromHeader);
Assert.AreEqual(cookieVal, valueFromHeader);
}
else
{
Assert.IsNull(valueFromHeader);
}
}