区域未传递给 ASP.net 核心中的 Url.Action()

Area is not passed to Url.Action() in ASP.net Core

以下代码在正常 ASP.net MVC 中工作。

Url.Action("actionName", "controllerName", new { Area = "areaName" });

但它在 ASP.net Core 中运行不佳。区域被识别为查询字符串参数。

我该如何解决? 感谢您的帮助。

确保您注册的路线如下:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "areaRoute",
        // if you don't have such an area named as `areaName` already, 
        //    don't make the part of `{area}` optional by `{area:exists}`
        template: "{area}/{controller=Home}/{action=Index}");  

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

我可以通过更改路由顺序或将 {area} 更改为可选来重现与您相同的问题。

  1. 订单很重要areaRoute 应该排在第一位。不要改变顺序。
  2. 生成url区域时,如果您还没有这样的区域,请不要将{area}部分改为{area:exists} 可选。例如,假设您正在尝试在 MyAreaName:

    的区域生成 url
    Url.Action("actionName", "controllerName", new { Area = "MyAreaName" });
    

    如果您的项目中没有名为 MyAreaName 的区域,并且您通过以下方式创建了区域 optional

    routes.MapRoute(
        name: "areaRoute",
        template: "{area:exists}/{controller=Home}/{action=Index}");
    

    生成的 url 将是 controllerName/actionName?Area=MyAreaName