Đây là một phiên bản sửa đổi từ @Roman như một phương pháp mở rộng với một chút ít LINQ và chính xác hơn mà không cần dùng StartsWith
mà có thể gây ra kết quả sai lệch nếu 2 hoặc nhiều cookie được bắt đầu với cùng tên
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;
}
Một số thử nghiệm đơn vị (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);
}
}