How to properly redirect (while setting a cookie)

2019-04-09 10:19发布

问题:

First off, I get the feeling that Response.Redirect is just a leftover from classic ASP, and I should be using something else in the MVC paradigm.

And second, while my current implementation of Response.Redirect IS working, it doesn't set the cookie I want it to. I'm assuming this is because the header gets wiped out instead of sent to the client on redirect.

Here is what I have so far:

    [HttpPost]
    public ActionResult Login(FormCollection form)
    {
        User user;
        string sessionKey;

        if (UserManager.Login(form["Email"], form["Password"]))
        {
            // Login stuff here

            // Remember user's email
            Response.Cookies["Email"].Value = form["Email"];
            Response.Cookies["Email"].Expires = DateTime.Now.AddDays(31);

            // Redirect to homepage
            Response.Redirect("~/");
        }
     }

回答1:

The proper way to redirect in MVC is return RedirectToAction("Home", "Index").

The cookies should work.