Home > Net >  Redirect to Account/Login view in asp.net core 7, from an anonymous action method of a controller
Redirect to Account/Login view in asp.net core 7, from an anonymous action method of a controller

Time:02-02

Home/Index is my default route of asp.net core application. In this method "index" of controller "Home", I need to check if the user is signed in or not, if the user is signed in, the user will be redirected to a special page according to role of the user. In other case, the user will be redirected to login page.

But login page is not being displayed and also not being shown any error message like the page is not found.

I tried following different options after studying articles in stackoverflow and other sites

return RedirectToAction("Login", "Account");
return RedirectToAction("Login", "Account", new {area = "Identity"});
return RedirectToAction("Login", "Account", new {area = ""});
return RedirectToAction("Login", "Identity/Account", new {area = ""});
return Redirect("/Account/Login");

But if applied [Authorize] attribute, then Account/Login page is being shown. So please guide me how to handle this scenario.

Following is given the complete flow and logic

public IActionResult Index()
{
    if (_userManager.IsSignedIn(User))
    {
        return RedirectToAction("MyDetails", "SupAdmin");
    }
    else
    {
        return RedirectToAction("Login", "Account");
        return RedirectToAction("Login", "Account", new {area = "Identity"});
        return RedirectToAction("Login", "Account", new {area = ""});
        return RedirectToAction("Login", "Identity/Account", new {area = ""});
        return Redirect("/Account/Login");
    }
}

CodePudding user response:

I try the below code, then it displays the login view:

public IActionResult Index()
        {
                return RedirectToAction("Login", "Account");
        } 

CodePudding user response:

i hope this is what you want to do, but since i think i was in the same issue as you here you go:

If you want to call, for example "Login.cshtml" or "Register.cshtml" from a own Controller (example: HomeController) you need to return the View() instead of redirecting to it. Here is some code for explanation:

[HttpPost]
    public ActionResult Register()
    {
        return View("/Areas/Identity/Pages/Account/Register.cshtml");
    }

This function gets Called when the user clicks a button by an Ajax.Post. After that redirects to Identity/Register View. Make sure to check the route of the view, yours might be different from mine.

  • Related