C# asp.net mvc中的Cookie未设置
我正在经历一种奇怪的情况。仅当字符串为硬编码时,集合cookie才会持久化C# asp.net mvc中的Cookie未设置,c#,asp.net-mvc,cookies,C#,Asp.net Mvc,Cookies,我正在经历一种奇怪的情况。仅当字符串为硬编码时,集合cookie才会持久化 public void OnActionExecuted(ActionExecutedContext filterContext) { if (filterContext.HttpContext.Items["Theam"] != null) { var sTheam = filterContext.HttpContext.Items["Theam"].ToString();
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);
}
}
无论我做什么,饼干都不会持久。只有将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();
}
}
}
关于这一行:
if (filterContext.HttpContext.Items["Theam"] != null)
Items是请求级别设置。这意味着您需要在每个HTTP请求上重新加载它。如果在运行这段代码之前未在请求生命周期的某个位置设置HttpContext.Items[Theam],则它将始终为空
我不确定这是否是您的问题,但这可以解释为什么在手动设置变量时,其余代码仍在工作。如果您以这种方式添加cookie,会发生什么情况Response.Cookies.AddtheamCookie;这个值是如何声明的。。?这是一个常量字符串。。可能正在将其设置为string.Empty某处..filterContext.HttpContext.Current.Response.Cookies.AddTheamCookie发现问题。首先,我感谢大家抽出时间。问题是我使用的是ajax调用。这个ajax调用确实在服务器上调用了action方法。请求从操作过滤器的OnActionExecutING发送到控制器中的ActionMethod,然后返回到OnActionExecutED。到目前为止,一切都很顺利。但是,因为这是一个ajax调用,所以在此之后会发生一些事情,并且没有设置cookie。因此,不要通过ajax调用设置cookie。现在我使用'@Url.actionsetheam'看到这个了吗。