【发布时间】:2015-01-18 16:13:46
【问题描述】:
我遇到了奇怪的情况。仅当字符串被硬编码时,设置的 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 替换为“cupid”之类的值时,该值才会保留。那就是
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();
}
}
}
【问题讨论】:
-
如果你以这种方式添加你的cookie会发生什么
Response.Cookies.Add(theamCookie);这个值是如何声明的......?TheamCookie它是一个 const 字符串吗.. 也许这被设置为 string.Empty 某处.. -
filterContext.HttpContext.Current.Response.Cookies.Add(theamCookie)
标签: c# asp.net-mvc cookies