我的asp.net MVC项目存在问题,我使用cookie来保存用户的数据 成功登录后,我使用以下代码设置cookie:
[HttpPost]
public ActionResult Index(string username,string password)
{
User user = db.Users.Where(t => t.username == username && t.password == password).SingleOrDefault();
if (user != null)
{
HttpCookie aCookie = new HttpCookie("cookie");
aCookie.Values["username"] = username;
aCookie.Values["role"] = user.role.ToString();
aCookie.Values["UserID"] = user.UserID.ToString();
aCookie.Values["route"] = "AdminReports";
aCookie.Secure = false;
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
isLogedIn = true;
return RedirectToAction("AdminReports", "Home");
}
TempData["ErrorMessage"] = "Wrong username or password!";
return View();
}
我使用以下代码阅读cookie:
public ActionResult AdminReports()
{
Response.Write(Server.HtmlEncode(Request.Cookies["cookie"]["username"]));
// Response.Write(Request.Cookies["cookie"]["username"]);
if (Request.Cookies["cookie"] != null)
{
if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.Admin)
{
return View();
}
else if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.The70Hospitals)
{
return View("The70Hospitals");
}
else if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.The380Hospitals)
{
return View("The380Hospitals");
}
else
{
return View("LoginView");
}
}
else
{
return View("LoginView");
}
}
然而,cookie会丢失其数据,导致用户无法登录。当我远程访问项目时会发生这种情况。但是它在开发模式下本地工作正常,并且当我从IIS浏览(在服务器中本地运行)时它也能正常运行
答案 0 :(得分:0)
检查您的web.config文件,
您可以在<system.web>
部分
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
使用System.Web.HttpCookie.HttpOnly
属性
希望这有帮助。