Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly redirect (while setting a cookie) in MVC3/Razor?

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("~/");
        }
     }
like image 361
Neil N Avatar asked Jun 16 '11 13:06

Neil N


People also ask

What is redirect to route in MVC?

RedirectToRouteResult is an ActionResult that returns a Found (302), Moved Permanently (301), Temporary Redirect (307), or Permanent Redirect (308) response with a Location header. Targets a registered route. It should be used when we want to redirect to a route.

What is Aspnet cookies cookie?

A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.

How do cookies work in MVC?

In ASP.Net MVC application, a Cookie is created by sending the Cookie to Browser through Response collection (Response. Cookies) while the Cookie is accessed (read) from the Browser using the Request collection (Request. Cookies).

What is cookies in C sharp?

Cookies is a small piece of information stored on the client machine. This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie" path. Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines.


1 Answers

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

The cookies should work.

like image 187
SLaks Avatar answered Oct 20 '22 14:10

SLaks