2014-04-23 83 views
9

我試圖讀取在ApiController語言Cookie(這是我在客戶端上設置)在我的後端Web API是這樣的:的.NET Web API - 的getCookie()返回空集

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

和我的要求標題是這樣的: enter image description here

還行

Request.Headers.GetCookies(); 

返回一個空集... 任何人可以牛逼我的理由是什麼,我能做些什麼呢? 請幫忙

回答

2

CookieHeaderValue的解析將失敗,因爲'?'在你的認證cookie名稱中。嘗試刪除問號。

2

這裏是餅乾提取的「完全手冊」很醜陋的手段:

/// <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; 
    } 

你的基地或庫班可見添加這個方法到您的網絡API控制器。

希望這會爲您節省一些時間。

乾杯。

1

下面是@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); 
    }     
}