2014-11-20 266 views
0

我遇到了奇怪的情況。只有當字符串是硬編碼時,設置的cookie纔會持續存在。在asp.net mvc Cookie中未設置

public void OnActionExecuted(ActionExecutedContext filterContext) 
{ 
    if (filterContext.HttpContext.Items["Theam"] != null) 
    { 
     var sTheam = filterContext.HttpContext.Items["Theam"].ToString(); 

     HttpCookie theamCookie = new HttpCookie("TheamCookie"); 

     theamCookie.Values.Add("TheamVal", sTheam); 
     theamCookie.Expires = DateTime.UtcNow.AddDays(5); 
     HttpContext.Current.Response.Cookies.Add(theamCookie); 
    } 
} 

不管我做什麼cookie不會持久。只有在將sTheam替換爲「丘比特」之類的值時,該值纔會持續。那是

theamCookie.Values.Add("TheamVal", "cupid"); 

工作,沒有別的。

任何人都可以對發生的事情有所瞭解嗎?我筋疲力盡,完全沒有選擇。經過8個多小時的調試,我意識到這一點。但不知道爲什麼會發生這種情況。請幫忙。

更新:以下是CookieFilter。這是一個ASP.NET MVC應用程序。

public class CookieFilter : IActionFilter 
{ 
    //private const string sTheamCookieName = "TheamCookie"; 
    public void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     if (filterContext.HttpContext.Items["TheamToBrowser"] != null) 
     { 
      var sTheam = ((string)(filterContext.HttpContext.Items["TheamToBrowser"])).ToString(CultureInfo.InvariantCulture); 

      HttpCookie theamCookie = new HttpCookie("TheamCookie"); 


      theamCookie.Values["TheamVal"] = "shamrock"; 
      theamCookie.Expires = DateTime.UtcNow.AddDays(5); 
      filterContext.HttpContext.Response.Cookies.Add(theamCookie); 
     } 
    } 

    public void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     HttpContextBase context = filterContext.HttpContext; 
     HttpCookie theamCookie = context.Request.Cookies["TheamCookie"]; 

     if (theamCookie == null) 
      context.Items["TheamFromBrowser"] = "default"; 
     else 
     { 
      if (string.IsNullOrEmpty(theamCookie.Value)) 
      { 
       context.Items["TheamFromBrowser"] = "default"; 
      } 
      else 
       context.Items["TheamFromBrowser"] = theamCookie.Values["TheamVal"].ToString(); 
     } 
    } 
} 
+0

如果以這種方式添加cookie,會發生什麼情況'Response.Cookies.Add(theamCookie);'這個值是如何聲明的? 'TheamCookie'sis是一個常量字符串..也許這是設置爲string.Empty某處.. – MethodMan 2014-11-20 17:28:32

+0

filterContext.HttpContext.Current.Response.Cookies.Add(theamCookie) – 2014-11-20 18:26:51

+0

http://stackoverflow.com/questions/6227222/我怎麼做我添加一個cookie爲每個訪客到我的ASP網絡mvc網站 – MethodMan 2014-11-20 19:51:47

回答

0

關於這條線:

if (filterContext.HttpContext.Items["Theam"] != null) 

HttpContext.Items是請求級別設置。這意味着您需要在每個HTTP請求上重新加載它。如果您在運行此代碼之前未在請求生命週期的某個位置設置HttpContext.Items["Theam"],它將始終爲空。

我不確定這是否是您的問題,但它可以解釋爲什麼手動設置變量時代碼的其餘部分工作正常。

+0

我發現這個問題。首先,我感謝你的每一個人。 – VivekDev 2014-11-22 01:12:44

+0

我發現了這個問題。首先,我感謝你的每一個人。問題是我正在使用ajax調用。這個ajax調用確實會調用服務器上的操作方法。該請求從操作過濾器的OnActionExecuting到控制器中的ActionMethod,然後返回到OnActionExecutED。在這一點上,每件事情都很好。但是因爲這是一個Ajax調用,所以在這之後會發生一些事情並且Cookie沒有設置。所以不要通過ajax調用設置cookie。看到這個http://stackoverflow.com/questions/8908345/unable-to-update-cookie-in-asp-net現在我使用'@ Url.Action(「SetTheam」)'。 – VivekDev 2014-11-22 01:20:16