2014-04-23 22 views
9

Tôi cố gắng để đọc một cookie ngôn ngữ (mà tôi đặt trên máy khách) trong một ApiController trong backend Web API của tôi như thế này:Net Web API - GetCookie() trả về bộ sưu tập trống

var cookieHeaderValue = Request.Headers.GetCookies("lang").FirstOrDefault(); 

và yêu cầu của tôi tiêu đề như sau: enter image description here

cũng là dòng

Request.Headers.GetCookies(); 

trả về một Bộ sưu tập trống ... Can ai t ell của tôi tại sao và những gì tôi có thể làm chống lại nó? Vui lòng giúp

Trả lời

2

Việc phân tích cú pháp CookieHeaderValue sẽ không thành công do '?' trong tên cookie xác thực của bạn. Hãy thử xóa dấu chấm hỏi.

2

Đây là một phương tiện "hoàn toàn bằng tay" và rất xấu xí của khai thác cookie:

/// <summary> 
    /// Retrieves an individual cookie from the cookies collection 
    /// </summary> 
    /// <param name="request"></param> 
    /// <param name="cookieName"></param> 
    /// <returns></returns> 
    public static string GetCookie(HttpRequestMessage request, string cookieName) 
    { 
     //var vHeaders = request.Headers; 
     //foreach (var vHeader in vHeaders) 
     // System.Diagnostics.Debug.WriteLine(vHeader.Key + " - " + vHeader.Value); 

     var vCookies = request.Headers.Where(H => H.Key.ToLower() == "cookie"); 
     if (vCookies != null) 
     { 
      var vArrCookie = vCookies.FirstOrDefault().Value; 
      if (vArrCookie != null) 
      { 
       var vCookiePair = 
        vArrCookie.FirstOrDefault().Split(new char[] { ';' }).Where(C => C.Trim().StartsWith(cookieName)).FirstOrDefault(); 
       if (vCookiePair != null) 
       { 
        //System.Diagnostics.Debug.WriteLine(vCookiePair); 
        var vCookie = vCookiePair.Trim().Substring(cookieName.Length + 1); 
        return vCookie; 
       } 
      } 
     } 

     // DID NOT WORK 

     //CookieHeaderValue cookie = request.Headers.GetCookies(cookieName).FirstOrDefault(); 
     //if (cookie != null) 
     // return cookie[cookieName].Value; 

     return null; 
    } 

Thêm phương pháp này để cơ sở của bạn hoặc lớp thư viện có thể nhìn thấy điều khiển Web Api của bạn.

Hy vọng điều này sẽ giúp bạn tiết kiệm thời gian.

Chúc mừng.

1

Đâ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); 
    }     
} 
Các vấn đề liên quan