MVC5:将两个不同的 url 路由到一个操作方法中,通过输入参数指定它们

MVC5: route two different urls into one action method designating them by the input parameter

假设我有以下操作方法:

[Route("option/{id:int}")] // routing is incomplete
public ActionResult GetOption(int id, bool advanced)
{
    ...
    return View();
}

此操作应与两个不同的路由相关联:

重要的是将这些路由表示为 两个单独的 url,而不是使用可选查询字符串参数的 URL。这些 URL 之间的唯一区别在于最后一项,这基本上是某种形式的指定。我需要的是一种设置路由规则的方法,以告诉框架它应该为两种类型的请求调用相同的方法,在 'advanced' 请求的情况下将 true 作为第二个参数传递,否则为假。我需要将两个路由封装到一个操作方法中有很多原因。所以,不,我不能添加第二种方法来单独处理 'advanced' 请求。

问题是:如何设置这样的路由?

如果你能改变第二个参数的类型

[HttpGet]
[Route("option/{id:int}")] // GET option/1
[Route("option/{id:int}/{*advanced}")] // GET option/1/advanced
public ActionResult GetOption(int id, string advanced) {
    bool isAdvanced = "advanced".Equals(advanced);

    //...

    return View();
}

尽管您需要执行单独的操作,但您可以简单地让一个调用另一个来避免重复代码(DRY)

// GET option/1
[HttpGet]
[Route("option/{id:int}")] 
public ActionResult GetOption(int id, bool advanced = false) {
    //...    
    return View("Option");
}

// GET option/1/advanced
[HttpGet]
[Route("option/{id:int}/advanced")]
public ActionResult GetAdvancedOption(int id) {
    return GetOption(id, true);
}