Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent logged in users from accessing login page in asp.net mvc 5

I have been trying to make my login page unreachable to already logged in users. They should rather be redirected to their dashboard unless they are not logged in.

I have done the following and neither of them is working. Anyone with a solution please?

    // GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        if (Request.IsAuthenticated)
        {
            RedirectToAction("Index", "Dashboard");
        }

        ViewBag.ReturnUrl = returnUrl ?? Url.Action("Index","Dashboard");
        return View();
    }

And this too

  // GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        if (User.Identity.IsAuthenticated)
        {
            RedirectToAction("Index", "Dashboard");
        }            
        ViewBag.ReturnUrl = returnUrl ?? Url.Action("Index","Dashboard");
        return View();
    }

Any guide will be appreciated. Thank you

like image 923
Josh Avatar asked Dec 19 '25 10:12

Josh


1 Answers

Sorry, I just observed that I was omitting the "return" on the line that ought to redirect the user.

I have added that and it now works

This is the correct code below

 // GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    if (User.Identity.IsAuthenticated)
    {
        return RedirectToAction("Index", "Dashboard");
    }            
    ViewBag.ReturnUrl = returnUrl ?? Url.Action("Index","Dashboard");
    return View();
}
like image 52
Josh Avatar answered Dec 22 '25 00:12

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!