Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 3.1 Razor Pages: How to automatically redirect to Login page from Index page?

I am building a web application using the ASP.NET Core 3.1 MVC and Razor pages.

I am new to Razor pages.

I created a basic application using above. I want to load the Login page on start of the application but the Index.cshtml page seems to be the start page.

To redirect from the Index.cshtml page (start page) to my Login.cshtml page, I did following in the Index.cshtml PageModel. But it is not working.

EDITED:

Index.cshtml:

    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
        <form method="get" asp-page="Index" hidden name="myForm">
            <input type="submit" name="submit" value="Redirect 1" asp-page-handler="Redirect1" hidden />
        </form>
    </div>

Index.cshtml.cs:

public class IndexModel : PageModel
    {
        public IndexModel() 
        {
          OnPostRedirect1();
        }
        public void OnGet() {}
        public IActionResult OnPostRedirect1()
        {
            return RedirectToPage("Login");
        }        
    }

How to automatically redirect to Login page from Index page?

like image 639
devman Avatar asked Sep 19 '25 18:09

devman


1 Answers

You have some options. If you don't want unauthorised users to visit the Index page, apply the [Authorize] attribute to the PageModel class:

[Authorize]
public class IndexModel : PageModel
{
    ...
}

Then, if your login page is not located at /account/login, configure the login page in Startup:

services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/YourLoginPage";
});

The framework will automatically redirect unauthenticated users to the login page. This is what most people are likely to do. Or, if you don't want Index at all, remove it and set the login page as the home page by changing its route template:

 @page "/"

This will override the conventional route for the page, based on its file path: https://www.learnrazorpages.com/razor-pages/routing#override-routes

like image 177
Mike Brind Avatar answered Sep 23 '25 06:09

Mike Brind



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!