I have a controller with this code. I want all actions to be /Action/Controller
or /{culture}/Action/Controller
except for Login which should be /Login
or /{culture}/Login
. Route works fine but Link is generated always as /Accounts/Login
or /{culture}/Accounts/Login
...
[Route("[controller]/[action]")]
[Route("/[controller]/[action]")]
public class AccountsController : Controller
{
[Route("/Login", Order = 0)]
[Route("/{culture}/Login", Order = 1)]
public IActionResult Login(short? showLostPasswordInfo)
{
return View(model);
}
}
Link looks like this
<a asp-action="Login">...</a> //outputs /Accounts/Login
I want it to point to /Login but it keeps generating wrong link.
Configuration in Startup.cs looks like this
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/health");
endpoints.MapControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}");
endpoints.MapControllerRoute(
name: "cultureDefault",
pattern: "{culture:culture}/{controller}/{action}");
});
});
CodePudding user response:
Link is generated always as /Accounts/Login or /{culture}/Accounts/Login...
[Route("[controller]/[action]")] [Route("/[controller]/[action]")]
Beacuse you put the [controller] in front of the [action],so the link as /controller/action
You can try to change the code that in front of the controller as below. To show other works well, I add index() .
[Route("[action]/[controller]")]
public class AccountsController : Controller
{
[Route("/Login", Order = 0)]
[Route("/{culture}/Login", Order = 1)]
public IActionResult Login(short? showLostPasswordInfo)
{
return View();
}
public IActionResult Index()
{
return View();
}
....
}
To see the result clearly, I add something in _layout.cshtml as below.
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Accounts" asp-action="Login">Login</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Accounts" asp-action="Index">Index2</a>
</li>
result:
CodePudding user response:
I found solution. There was another Login method in AccountsController for HttpPost which didn't have any Route attribute. Adding same attributes to second method solved the problem.