2016-08-05 44 views
1

我已經按照我的Home -controller代碼:爲什麼我不能刪除一個cookie?

public ActionResult MyPage() 
{ 
    if (HttpContext.Request.Cookies["User"] == null) 
    { 
     //Create cookie 
     return RedirectToAction("MyPage", "Home"); 
    } 
    else 
    { 
     string User = HttpContext.Request.Cookies["User"].Value; 
     foreach (var user in Data.MyUsers) 
     { 
      if (user.username == User) 
      { 
       //Do some stuff 
       return View("MyPage"); 
      } 
     } 
     HttpContext.Request.Cookies.Remove("User"); 
     //HttpContext.Response.Cookies.Remove("User"); works not sorry ;(
     return RedirectToAction("MyPage", "Home"); 
    } 
} 

問題:應用程序不刪除cookie(爲什麼有的話),並在循環中運行,因爲應用程序沒有找到用戶數據。 (問題不在於應用程序未找到用戶,問題在於Cookie問題)

問題:我該如何解決此問題,因爲在另一個項目中,我工作正常。我在我的新項目中複製並粘貼來自其他項目的代碼,但是在新項目中它不起作用。是的,我用asp.net框架:)

希望你能幫助我...我在我的關於C#的訣竅結束的同一版本....

非常感謝你。

回答

3

使用過期屬性,並設置負值給它,這將到期你的話餅乾即這將刪除cookies列表。

String cookieName = Request.Cookies["User"].Name; 
HttpCookie userCookie = new HttpCookie(cookieName); 
userCookie.Expires = DateTime.Now.AddDays(-1); 
Response.Cookies.Add(userCookie); 
+0

對不起,它不是工作 – Yannik

+0

這工作,但它認爲沒有做到這一點... – Yannik

+0

按我的經驗,正確的方法和知識,這是我知道的唯一途徑 –

相關問題