Asp.net mvc controller 中如何正确存取cookie
我是这样写的://以下是存cookie,假设这是些在controllerA中,运行项目首先会走过这段代码,也就是cookie里面现在是有值的。HttpCookiecook...
我是这样写的 :
//以下是存cookie, 假设这是些在controllerA中,运行项目首先会走过这段代码,也就是cookie里面现在是有值的。
HttpCookie cookie = new HttpCookie("xx");
xx.Name = "Name";
xx.Expires = DateTime.Today.AddDays(365);
xx.Values.Add("xx_Id", "Id");
Response.AppendCookie(cookie);
//以下是取cookie,假设是在controllerB中,运行完项目当我进行某一操作时,会走下面这段代码。 问题是 为什么现在的Request.Cookies["xx"] 是空的,???求解啊!!
if (Request.Cookies["xx"] != null) {
string X = Request.Cookies["xx"]["xx_Id"].ToString();} 展开
//以下是存cookie, 假设这是些在controllerA中,运行项目首先会走过这段代码,也就是cookie里面现在是有值的。
HttpCookie cookie = new HttpCookie("xx");
xx.Name = "Name";
xx.Expires = DateTime.Today.AddDays(365);
xx.Values.Add("xx_Id", "Id");
Response.AppendCookie(cookie);
//以下是取cookie,假设是在controllerB中,运行完项目当我进行某一操作时,会走下面这段代码。 问题是 为什么现在的Request.Cookies["xx"] 是空的,???求解啊!!
if (Request.Cookies["xx"] != null) {
string X = Request.Cookies["xx"]["xx_Id"].ToString();} 展开
2个回答
展开全部
给你一个完整的例子,看了后自然明白怎么回事了。
public class CookieController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
string cookie = "There is no cookie!";
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
{
cookie = "Yeah - Cookie: " + this.ControllerContext.HttpContext.Request.Cookies["Cookie"].Value;
}
ViewData["Cookie"] = cookie;
return View();
}
public ActionResult Create()
{
HttpCookie cookie = new HttpCookie("Cookie");
cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
return RedirectToAction("Index", "Home");
}
public ActionResult Remove()
{
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
cookie.Expires = DateTime.Now.AddDays(-1);
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
}
return RedirectToAction("Index", "Home");
}
}
更多追问追答
追问
看您代码里头没有设置时间,,,请问 ,我上面的那些代码的写法对吗,?在别的controller调我已经存过的cookie为什么得到的是空呢,是没存进去吗?
追答
你当然可以自己设置过期时间,这块我只是默认的。
你这个xx好像不对吧,xx是Cookie对象的name, 试一下下面的代码,
HttpCookie cookie = new HttpCookie("xx");
cookie.Name = "Name";
cookie.Expires = DateTime.Today.AddDays(365);
cookie.Values.Add("xx_Id", "Id");
Response.Cookies.Add(cookie);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询