在 Asp.Net Mvc 4 中使用 Cookie [英] Using Cookie in Asp.Net Mvc 4
问题描述
我在 Asp.Net MVC4 中有 Web 应用程序,我想使用 cookie 进行用户登录和注销.所以我的操作如下:
I have web application in Asp.Net MVC4 and I want to use cookie for user's login and logout. So my actions as follows:
登录操作
[HttpPost]
public ActionResult Login(string username, string pass)
{
if (ModelState.IsValid)
{
var newUser = _userRepository.GetUserByNameAndPassword(username, pass);
if (newUser != null)
{
var json = JsonConvert.SerializeObject(newUser);
var userCookie = new HttpCookie("user", json);
userCookie.Expires.AddDays(365);
HttpContext.Response.Cookies.Add(userCookie);
return RedirectToActionPermanent("Index");
}
}
return View("UserLog");
}
退出操作
public ActionResult UserOut()
{
if (Request.Cookies["user"] != null)
{
var user = new HttpCookie("user")
{
Expires = DateTime.Now.AddDays(-1),
Value = null
};
Response.Cookies.Add(user);
}
return RedirectToActionPermanent("UserLog");
}
我在 _Loyout 中使用这个 cookie 如下:
And I use this cookie in _Loyout as follow:
@using EShop.Core
@using Newtonsoft.Json
@{
var userInCookie = Request.Cookies["user"];
}
...
@if (userInCookie != null && userInCookie.Value)
{
<li><a href="#">Salam</a></li>
<li><a href="@Url.Action("UserOut", "Home")">Cıxış</a></li>
}
else
{
<li><a href="@Url.Action("UserLog", "Home")">Giriş</a></li>
}
但是当我 单击 *UserOut* 操作时,此操作第一次发生,但随后不起作用.我为查找过程设置了断点,但它得到 UserLog 操作没有 UserOut.我的问题是我在哪里使用了错误的 cookie 方式?对于这种情况,在 Asp.Net Mvc4 中使用 cookie 的最佳方法是什么?
But When I click *UserOut* action this action happen first time, but then it doesn't work. I put breakpoint for looking process but it get UserLog action doesn't UserOut. My question is that where I use wrong way of cookie? What is a best way using cookie in Asp.Net Mvc4 for this scenario ?
推荐答案
尝试使用 Response.SetCookie()
,因为 Response.Cookies.Add()
会导致多个要添加的 cookie,而 SetCookie
将更新现有的 cookie.
Try using Response.SetCookie()
, because Response.Cookies.Add()
can cause multiple cookies to be added, whereas SetCookie
will update an existing cookie.
这篇关于在 Asp.Net Mvc 4 中使用 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!