2014-11-20 54 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