Jakob Lithner
Jakob Lithner

Reputation: 4416

Different default page in MVC if authenticated

This might be a very simple question, but I have a hard time to understand the MVC routing.

Scenario: The user enters my site by entering www.mydomain.com in his browser. I would like to redirect to different default pages depending on if the user is authenticated or not.

My current authentication approach: In Application_PostAuthenticateRequest I check for a FormsAuthentication cookie. If found I parse user principal from cookie.

Where and how should I configure the redirect?

Upvotes: 2

Views: 2160

Answers (1)

Tommy
Tommy

Reputation: 39807

I am not sure what the second part of your question really is supposed to mean, however, the main part of your question should be pretty straightforward. This has nothing to do with "routing", just what you want to happen if someone comes to your index (root) page of your site.

Let's say this is your controller/action

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult AuthenticatedIndex()
    {
        ViewBag.Message = "Your application description page.";

        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }        
}

To test if someone is authenticated in a controller/action, you can use this line of code:

User.Identity.IsAuthenticated

which returns true/false depending on if the user is authenticated. Next, we need to send the user somewhere else if they are authenticated. That is done by using the following:

RedirectToAction("actionName", "controllerName");

So, if we tie all of this together, we can now update our Index() method and send the user somewhere else if they are authenticated.

public ActionResult Index()
{
    if(User.Identity.IsAuthenticated){
         //send them to the AuthenticatedIndex page instead of the index page
         return RedirectToAction("AuthenticatedIndex", "Home");
    }
    return View();
}

The only caveat I see here is that a logged in user will Never be able to get to the Index method, which may be what you want.

Upvotes: 4

Related Questions