2012-12-27 48 views
3

我正在測試以查看用戶是否打開了Cookie,並且我似乎沒有正確地做某件事。我的Cookie測試不起作用

這裏是我的測試:

private bool CookiesAllowed() 
{ 
    var testCookie = new HttpCookie("TestCookie", "abcd"); 
    System.Web.HttpContext.Current.Response.Cookies.Set(testCookie); 

    var tst = System.Web.HttpContext.Current.Request.Cookies.Get("TestCookie"); 
    if (tst == null || tst.Value == null) 
    { 
    return false; 
    } 
    return true; 
} 

我把一個cookie在那裏......然後得到它回來。但它總是成功。

這裏是我如何禁用它們:

enter image description here

我登錄到Gmail,它告訴我,我的cookie被禁用,所以我相信我做的那部分權利。

我在做什麼錯?

編輯

要回答詹姆斯的問題,我從我的登錄屏幕,這是我的輸入畫面作爲第一個檢查調用此:

public ActionResult LogOn(string id) 
    { 
     if (!CookiesAllowed()) 
     { 
     return View("CookiesNotEnabled"); 
     } 

另外,我還測試了這個活,在視覺工作室之外,而不是在本地主機,它做了同樣的事情。

+0

你在哪裏調用這段代碼? – James

+0

也許你應該看看[最好的方式來確定是否在ASP.NET中啓用cookie?](http://stackoverflow.com/questions/210321/best-way-to-determine-if-cookies-are- enabled-in-asp-net) –

回答

2

你必須讓你的客戶端/瀏覽器做一個新的請求,看看你是否得到了cookie。當您將Cookie添加到響應對象時,您只能在隨後的新請求中檢查它的存在。

這裏有一個方法來在ASP.NET Web窗體同一頁面內做到這一點(因爲我看到了你的編輯說明您正在使用MVC):

private bool IsCookiesAllowed() 
{ 
    string currentUrl = Request.RawUrl; 

    if (Request.QueryString["cookieCheck"] == null) 
    { 
    try 
    { 
     var testCookie = new HttpCookie("SupportCookies", "true"); 
     testCookie.Expires = DateTime.Now.AddDays(1); 
     Response.Cookies.Add(testCookie); 

     if (currentUrl.IndexOf("?", StringComparison.Ordinal) > 0) 
     currentUrl = currentUrl + "&cookieCheck=true"; 
     else 
     currentUrl = currentUrl + "?cookieCheck=true"; 

     Response.Redirect(currentUrl); 
    } 
    catch 
    { 
    } 
    } 

    return Request.Cookies.Get("SupportCookies") != null; 
} 

這段代碼是由this thread啓發。

+0

Bingo!就是這樣!謝謝您的幫助! – ErocM

+0

這段代碼看起來很像[這個答案](http://forums.asp.net/t/1044823.aspx) - 如果是的話,你應該引用源代碼 – James