Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop user going to Login/Register & Other non Authenticated pages on MVC3 application?

Once user logins to my site where i use Form Authentication then how can i stop user to going on Login & Register page if he has allready login & register.

like image 236
updev Avatar asked Mar 16 '12 19:03

updev


2 Answers

Two ways "off the top of my head":

1 - Custom Action Filter that redirects the user from the page if they are logged in.

public class RedirectAuthenticatedRequests : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.HttpContext.Request.IsAuthenticated) {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(new {
                        controller = "SomeController",
                        action = "SomeAction"
                }
            ));
        }

        base.OnActionExecuting(filterContext);
    }
}

2 - Simple check in the login action method if the user is logged in.

if(Request.IsAuthenticated) return RedirectToAction("SomeOtherView");
like image 102
Alex Avatar answered Sep 28 '22 08:09

Alex


The easy way out is checking in the controller method(login/register) if the user is authenticated, and if it is redirect the user to the page you want:

Something like this for the Login page(same with Register):

//
// GET: /Login/Index
public ActionResult Index()
{
     if(User.Identity.IsAuthenticated){
          //redirect to some other page
          return RedirectToRoute("Home", "Index"); 
     }

     return View();
}
like image 21
Cacho Santa Avatar answered Sep 28 '22 08:09

Cacho Santa