未在asp.net MVC中设置Cookie [英] Cookie not setting in asp.net mvc
本文介绍了未在asp.net MVC中设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
if (HttpContext.Request.Cookies["time"]==null)
{
HttpCookie cookie = new HttpCookie("last_visited",DateTime.Now.ToString());
cookie.Expires = DateTime.Now.AddDays(10);
HttpContext.Response.Cookies.Add(cookie);
}
else if(HttpContext.Request.Cookies["last_visited"]!=null)
{
ViewBag.last_visited = HttpContext.Request.Cookies["last_visited"].Value;
}
我正在尝试在asp.net mvc中设置cookie。上面是我在contoller动作中的代码。这段代码的目的是在没有cookie的情况下设置cookie,在有cookie的情况下读取值。
I am trying to set a cookie in asp.net mvc. Above is my code in the contoller action. The purpose of this code is to set a cookie if there is none and read a value if there is a cookie set.
但是在设置断点后,我发现了else如果部分永远不会执行,就好像根本没有设置cookie。
However the after setting the breakpoint i discovered the else if part is never getting executed as if the cookie isn't being set up at all.
这里出了什么问题?
推荐答案
第一个if语句是否正在检查错误的cookie?应该将时间
改为最后一次访问
?
Is it that the first if statement is checking the wrong cookie? Should "time"
be "last_visited"
instead?
固定代码:
if (HttpContext.Request.Cookies["last_visited"]==null)
{
HttpCookie cookie = new HttpCookie("last_visited",DateTime.Now.ToString());
cookie.Expires = DateTime.Now.AddDays(10);
HttpContext.Response.Cookies.Add(cookie);
}
else if(HttpContext.Request.Cookies["last_visited"]!=null)
{
ViewBag.last_visited = HttpContext.Request.Cookies["last_visited"].Value;
}
这篇关于未在asp.net MVC中设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文