简体   繁体   中英

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

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?

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();

        }

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM