【问题标题】:Force route placeholder to be always treated as query string parameter强制路由占位符始终被视为查询字符串参数
【发布时间】:2016-01-20 20:40:13
【问题描述】:

我在具有路由前缀的控制器中的操作上有以下路由:

[Route("{page?}", Name = "MyRoute")]
public async Task<ActionResult> Index(int page = 1)

IUrlHelper.RouteUrl 给了我一个以 /1 结尾的 URL,用于 MyRoutePage = 1 作为路由值。这没有错,但我希望 page 始终是查询字符串参数。

如何在 MVC 6 中做到这一点?如果可能的话,我想避免自己解析RouteUrl 方法的结果并将页面设置为查询字符串参数。 Routing docs 仍然是空的。 This 答案建议使用 [FromUri]attribute 虽然听起来这有不同的目的,而且它似乎在 MVC 6 中不可用。

【问题讨论】:

    标签: asp.net-mvc-routing asp.net-core-mvc


    【解决方案1】:

    我通过在路由中没有参数{page?} 让它工作。

    最初我有[Route("Bar/{page?}", Name = "BarRoute")],它给了我/Bar/1

    我让它与一个动作设置一起工作,例如:

        [Route("Bar", Name = "BarRoute")]
        public IActionResult Foo(string page)
        {
            ViewBag.PN = page;
            return View("Index");
        }
    

    这个剃须刀标记:

    <li>@Html.RouteLink("Click here!", "BarRoute", new { page = 1 })</li>
    

    生成:

    <li><a href="/Bar?page=1">Click here!</a></li>
    

    在控制器中:

    ViewBag.Thing = this.Url.RouteUrl("BarRoute", new { page = 1 });
    

    给:

    /Bar?page=1
    

    另外,[Route("", Name = "BarRoute")] 生成了http://localhost:62405/?page=1

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2020-06-09
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      相关资源
      最近更新 更多