C# 在MVC5中加载视图之前访问cookie?
假设我有一个值为“OLD”的cookie,然后我用以下代码更新cookie:C# 在MVC5中加载视图之前访问cookie?,c#,asp.net-mvc,C#,Asp.net Mvc,假设我有一个值为“OLD”的cookie,然后我用以下代码更新cookie: var lang = new HttpCookie("lang"); lang.Value = "NEW"; lang.Expires = DateTime.UtcNow.AddDays(2); HttpContext.Current.Response.SetCookie(lang); //set updated cookie value var x = HttpContext.Current.Request.Co
var lang = new HttpCookie("lang");
lang.Value = "NEW";
lang.Expires = DateTime.UtcNow.AddDays(2);
HttpContext.Current.Response.SetCookie(lang); //set updated cookie value
var x = HttpContext.Current.Request.Cookies("lang");
x
仍将“OLD”作为值,因为它没有被发送到客户端。是否可以在不首先发送给客户端的情况下获取更新后的值?如果您不想将值发送给客户端,只想用作参考,则可以出于您的目的使用TempData
。这可能会有所帮助。我认为,您应该在响应中寻找它,而不是在请求中,因为请求-它来自客户端 问题
您正在HttpContext.Current.Response
中设置cookie,并尝试在下一个请求到达服务器之前在HttpContext.Current.Request
中找到它
这是行不通的
我的建议
在这种情况下,cookie的使用是不正确的。你还有其他更好的选择,比如-
HttpContext.Current.Response
中搜索cookie。我相信你会得到的
像这样:
var cookieValue = HttpContext.Current.Response.Cookies["OLD"].Value