简体   繁体   中英

ASP.NET Core MVC wrong link is generated

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}");
     });
});

You can try to change the code that in front of the controller as below:

        [Route("[action]/[controller]")]
        [Route("/[action]/[controller]")]
        public class AccountsController : Controller
        {
            
            [Route("/Login", Order = 0)]
            [Route("/{culture}/Login", Order = 1)]
    
            public IActionResult Login(short? showLostPasswordInfo)
            {
                return View();
            }
             ....
         }

result:

在此处输入图像描述

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.

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