C#自定义地图路线/视图路径/链接生成

问题描述 投票:0回答:1

问题/尝试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

问题/尝试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

c# routes actionlink html.actionlink custom-routes
1个回答
0
投票

URL映射一段时间后,我发现自定义映射的解决方案是在主RouteConfig.cs中添加,而不是在Area注册中添加。将MapRoute移至Area可以正常工作,并且Controller中没有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 })
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.