asp.net - ASP.Net MVC Cookies不持久

标签 asp.net asp.net-mvc asp.net-mvc-3 cookies

本质上,我试图在用户登录后设置Cookie,以在下次登录时保留其用户名。这是设置Cookie的代码。设置cookie后,当我在Firefox中查看站点cookie时,它显示的是sessionID cookie,而不是我刚刚设置的cookie。当我在Fiddler中检查标题时,我看不到它设置了cookie,仅设置了sessionID cookie。

HttpCookie hc = new HttpCookie("username", model.UserName);
hc.Expires = DateTime.Now.AddYears(1);
System.Web.HttpContext.Current.Request.Cookies.Add(hc);

这是我检查Cookie是否存在的地方。
if (System.Web.HttpContext.Current.Request.Cookies["username"] != null)

这是所讨论方法的完整上下文
public ActionResult LogOn()
{
    if (System.Web.HttpContext.Current.Request.Cookies["username"] != null)
        return View(new LogOnModel { UserName = System.Web.HttpContext.Current.Request.Cookies["username"].Value });
    else
        return View();
}

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            HttpCookie hc = new HttpCookie("username", model.UserName);
            hc.Expires = DateTime.Now.AddYears(1);
            System.Web.HttpContext.Current.Request.Cookies.Add(hc);

            FormsService.SignIn(model.UserName, model.RememberMe);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    return View(model);
}

最佳答案

添加到response.cookies不是request.cookies

关于asp.net - ASP.Net MVC Cookies不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5876573/

相关文章:

asp.net-mvc - 用于 Web.config <appSettings> 的 T4MVC

c# - 如何在 ASP.NET MVC C# 中为 jqPlot 图表返回多维数组作为 JSON

jquery - 在MVC3中使用CheckBoxFor时,如何使用JQuery仅选择CheckBox INPUT?

c# - 为什么在 ASP.Net Core 2 MVC 中更改密码后登录

css - Bootstrap 3 弹窗透明和样式问题?

c# - 找不到 Visual Studio 2015 上的 ASP.NET 5 addMvc 方法

ASP.NET 登录页面

jquery - 至少选择一个复选框 - Asp.Net MVC - jQuery

jquery - MVC 3 和 ajax 调用 - 无法阻止它缓存

c# - Controller 范围之外的 ControllerContext 和 ViewData - MVC3 C#