【问题标题】:C# Custom Map Routes / View Paths / Link GenerationC# 自定义地图路线/查看路径/链接生成
【发布时间】:2020-04-30 15:28:20
【问题描述】:

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

    网址映射
    一段时间后,我找到了我在主 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}
            );
        }
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 1970-01-01
      • 2012-05-20
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      相关资源
      最近更新 更多