【问题标题】:MVC Attribute routing with Url.Action not resolving route带有 Url.Action 的 MVC 属性路由未解析路由
【发布时间】:2016-07-16 05:09:13
【问题描述】:

根据我应用的属性路由,我无法让@Url.Action 解析为我期望的 url:

我的操作(SearchController 但使用 [RoutePrefix("add")])

     [Route("{searchTerm}/page/{page?}", Name = "NamedSearch")]
     [Route("~/add")]
     public ActionResult Index(string searchTerm = "", int page = 1)
     {
       ...
     }

调用 Url.Action

@Url.Action("Index", new { controller = "Search", searchTerm = "replaceMe", page = 1 })

这会产生一个 url

/add?searchTerm=replaceMe&page=1

我希望

/add/replaceMe/page/1

如果我手动输入 url,那么它会使用正确的参数解析为正确的操作。为什么@Url.Action 不能解析正确的url?

【问题讨论】:

    标签: asp.net-mvc routes url-routing asp.net-mvc-routing attributerouting


    【解决方案1】:

    由于您为漂亮的路线定义命名,您可以使用RouteUrl 方法。

    @Url.RouteUrl("NamedSearch", new {  searchTerm = "replaceMe", page = 1})
    

    由于您需要添加 url,您应该更新您的路由定义以将其包含在 url 模式中。

    [Route("~/add")]
    [Route("~/add/{searchTerm?}/page/{page?}", Name = "NamedSearch")]
    public ActionResult Index(string searchTerm = "", int page = 1)
    {
     // to do : return something
    }
    

    【讨论】:

    • 谢谢,为两条路线添加一个名称并使用 RouteUrl 是让这两条路线都能正常工作的唯一可靠方法。
    • 对于那些来到这里并希望在 ApiController 中获得操作路由的人:@Url.HttpRouteUrl 在这种情况下得到了诀窍;-)
    • 这帮助我将正确的路线传递给 Troy Goode 的 PagedList。绞尽脑汁将近一天!
    • 如果搜索词和页面是动态参数怎么办??
    【解决方案2】:

    路线是顺序敏感的。但是,属性不是。事实上,在像这样的单个操作上使用 2 个 Route 属性时,您可能会发现它适用于某些编译,而不适用于其他编译,因为反射在分析自定义属性时不保证顺序。

    为确保您的路由以正确的顺序输入到路由表中,您需要为每个属性添加Order 属性。

    [Route("{searchTerm}/page/{page?}", Name = "NamedSearch", Order = 1)]
    [Route("~/add", Order = 2)]
    public ActionResult Index(string searchTerm = "", int page = 1)
    {
        return View();
    }
    

    在您解决排序问题后,URL 会以您期望的方式解析。

    @Url.Action("Index", new { controller = "Search", searchTerm = "replaceMe", page = 1 })
    
    // Returns "/add/replaceMe/page/1"
    

    【讨论】:

    • 谢谢,如果我使用 @Html.ActionLink("Add Issues", "Index", new { controller =“搜索”})。我可以让它工作的唯一可靠方法是为两者添加名称。
    【解决方案3】:

    要返回完整的 URL 使用这个

    @Url.Action("Index", new { controller = "Search", searchTerm = "replaceMe", page = 1}, protocol: Request.Url.Scheme)
    
    // Returns "http://yourdomain.com/add/replaceMe/page/1"
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 2014-11-14
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多