ASP.NET Core Incorrect Route for LoginPath

210 views Asked by At

I have two controllers in the Controllers folder: HomeController and LoginController.

I am using cookie authentication and set the LoginPath to /Login, expecting it to route to the LoginController.

However, when I click on the login link, the app routes to Home/Login instead of /Login. How can it get it to route to /Login correctly?

Routes

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
    name: "login",
    pattern: "{controller=Login}/{action=Login}");

LoginPath:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
    options.LoginPath = "/Login";
    options.AccessDeniedPath = "/Home/Denied";
});

Folders:

Folders

1

There are 1 answers

0
Ruikai Feng On

Firstly, the codes options.LoginPath = "/Login"; would redirect you to https://localhost:xxxx/Login when you visit the endpoint has Authrize attribute on it if you're not authenticated;If the Login Action is in Login Controller,For your requirement,it should be "/Login/Login"

Secondly,

However, when I click on the login link, the app routes to Home/Login

it depends on how you configured the link,but you haven't show it.

you need a link like:<a asp-controller="Login" asp-action="Login"> Login </a>

And the second route parttern you configured is not necessary

You could check this document for more details