加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – ActionLink为Attribute Route生成错误的URL

发布时间:2020-12-16 09:55:30 所属栏目:asp.Net 来源:网络整理
导读:我正在使用属性路由来覆盖控制器中的URL.我有两个动作,唯一的区别是第二个动作中出现的ID.其余参数是用于搜索的可选查询参数. // RouteConfig.cs - I setup AttributeRoutes before any other mapped routes.routes.MapMvcAttributeRoutes();// Controllers/
我正在使用属性路由来覆盖控制器中的URL.我有两个动作,唯一的区别是第二个动作中出现的ID.其余参数是用于搜索的可选查询参数.

// RouteConfig.cs - I setup AttributeRoutes before any other mapped routes.
routes.MapMvcAttributeRoutes();

// Controllers/DeliveryController.cs
[Route("mvc/delivery")]
public ActionResult Delivery(string hauler,DateTime? startDate,DateTime? endDate,int? page)
{
    // ...
    return View(model);
}

[Route("mvc/delivery/{id}")]
public ActionResult Delivery(int id,string hauler,int? page)
{
    // ...
    return View("DeliverySelected",model);
}

当手动导航到/ mvc / delivery和/ mvc / delivery / 1234 /时,两个路由都按预期工作,但链接生成不正确.

@Html.ActionLink("Delivery","Delivery",new { id = delivery.ID })
@Url.Action("Delivery",new { id = delivery.ID })

这两种方法都会生成如下所示的链接,这会触发第一个操作而不是第二个操作:

http://localhost:53274/mvc/delivery?id=1234

如何生成预期的URL呢?

http://localhost:53274/mvc/delivery/1234

解决方法

由于 this answer concerning ambiguous action methods,我找到了答案.在控制器中,最多只能有2个具有相同名称的操作方法.

在这种情况下我确实有第三种方法,因为我认为它是不相关的,所以我遗漏了:

[HttpPost]
[Route("mvc/delivery")]
public ActionResult Delivery(DeliveryViewModel model)

将我的第二个动作重命名为SelectDelivery(int id,/ * … * /)解决了这个问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读