Home > Software design >  How can I redirect an already logged user to Index in Asp .Net Core web Application (razor pages)
How can I redirect an already logged user to Index in Asp .Net Core web Application (razor pages)

Time:07-26

I want to avoid users getting into the loggin page if already authenticated.

I know that you can use the RedirectToPage("/index") but i don`t know were.

I've tried this:

@page
@model xxxxx.Accounts.LoginModel
@{
    Layout = "EmptyLayout";
    if (User.Identity.IsAuthenticated)
          RedirectToPage("/index")
}

<!doctype html>
<html lang="es">
//login page

This don't work for me and I know that if (User.Identity.IsAuthenticated) is true, and in the PageModel the Redirect("") method works properly.

Is there any PageModel method like OnCreate(), OnLoad(),... to run code before the page is loaded? How can I achive this?

CodePudding user response:

I belive that i was not on debug mode so i didn't get the breakpoint on the OnGet(). So the solution is just to do this:

public async Task<IActionResult> OnGet()
        {
            if (User.Identity.IsAuthenticated)
                return Redirect("/Index");
            else return Page();

        }

CodePudding user response:

As you tested, the onget method is occurred when the page loading.

Besides, if you want to get other method which is early than the onget method. I suggest you could try filter method.

Razor Page filters:

Run code after a handler method has been selected, but before model binding occurs.

Run code before the handler method executes, after model binding is complete.

Run code after the handler method executes.

Can be implemented on a page or globally.

Cannot be applied to specific page handler methods.

Can have constructor dependencies populated by Dependency Injection (DI). For more information, see ServiceFilterAttribute and TypeFilterAttribute.

More details about how it works ,you could refer to this article.

  • Related