【发布时间】:2017-09-24 17:27:26
【问题描述】:
基本上,我正在尝试从 cookie 中获取字符串值..
如果我只是从请求中读取它.. 我可以得到很好的价值。 除了第一个页面加载,因为响应没有到达客户端并返回,所以请求没有我刚刚设置的值。
但是,奇怪的是..如果我访问 Response 并检查它是否存在(也就是刚刚设置的值).. 我可以得到这个值。但这会导致一些奇怪的错误(?),即 cookie 在下一次返回的请求中重复。
在第二个请求返回时,该值是从空白的重复请求 cookie 中读取的。 (又名,cookie 值不起作用)
保存
var request = url.RequestContext.HttpContext.Request;
var response = url.RequestContext.HttpContext.Response;
//STORE VALUES TO COOKIE
HttpCookie hc = new HttpCookie("myCookie");
hc.Expires = DateTime.Now.AddDays(1);
hc.Value = "MYVALUE";
request.Cookies.Add(hc);
response.Cookies.Add(hc);
阅读
public static string GetAdvancedCookieValue(this UrlHelper url, string cookieName)
{
var request = url.RequestContext.HttpContext.Request;
var response = url.RequestContext.HttpContext.Response;
// Accessing Response allows me to get value just set.. but leads to duplicate cookies (with blank data -causing blank return later)
if (response.Cookies[cookieName] != null && String.IsNullOrWhiteSpace(response.Cookies[cookieName].Value) == false)
return response.Cookies[cookieName].Value;
if (request.Cookies[cookieName] != null && String.IsNullOrWhiteSpace(request.Cookies[cookieName].Value) == false)
return request.Cookies[cookieName].Value;
return null;
}
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4 cookies