C#自定义地图路由/查看路径/Link代

C# Custom Map Routes / View Paths / Link Generation

Issue/Try 1:
我有一个自定义路线图:

routes.MapRoute(
    name: "User Profile",
    url: "User/{userId}/{controller}/{action}/{id}",
    defaults: new { Areas = "User", controller = "Kpi", action = "Index", id = UrlParameter.Optional }
);

如果我手动导航到 URL /User/f339e768-fe92-4322-93ca-083c3d89328c/Kpi/View/1 页面加载时出现查看错误:The view 'View' or its master was not found or no view engine supports the searched locations

Issue/Try 2:
停止使用自定义路由并将我的控制器设置为:

    [RouteArea("User")]
    [RoutePrefix("{userId}/Kpi")]
    public class KpiController : BaseUserController
    {
        [Route("View/{id}")]
        public async Task<ActionResult> View(string userId, int? id = null)
        {
            [...]
        }
    }

现在可以使用了,我可以导航到 URL 并且视图显示正常。

两者的问题:
虽然我可以手动导航到两者并且它们加载我似乎无法使用 ActionLink 正确生成 URL:

@Html.ActionLink(kpi.GetFormattedId(), "View", "Kpi", new { Area = "User", userId = Model.Id, id = kpi.Id }, null)

它生成:/User/Kpi/View/1?userId=f339e768-fe92-4322-93ca-083c3d89328c 而不是 /User/f339e768-fe92-4322-93ca-083c3d89328c/Kpi/View/1

URL映射
一段时间后,我找到了我在主 RouteConfig.cs 而不是 Area 注册中添加的自定义映射的解决方案。将 MapRoute 移动到 Area 可以正常工作,并且控制器中没有 RouteAreaRoutePrefixRoute 属性。

地区报名

public class UserAreaRegistration : AreaRegistration 
{
    public override string AreaName => "User";

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            name: "User",
            url: "User/{userId}/{controller}/{action}/{id}",
            defaults: new { action = "Index", id = UrlParameter.Optional }
        );

        context.MapRoute(
            "User_default",
            "User/{controller}/{action}/{id}",
            new {action = "Index", id = UrlParameter.Optional}
        );
    }
}

链接
而不是使用 ActionLink 我现在使用 RouteLink.

@Html.RouteLink("KPIs", "User", new { Controller = "Kpi", Action = "Index", userId = Model.Id })