2014-10-08 65 views
6

我试图在我的MVC 5 web应用中实现替代路由。MVC替代路由失败,可选参数

我的控制器代码:

namespace MyMvcProject.Web.Controllers 
{ 
    [RoutePrefix("account")] 
    public class AccountController : Controller { 


     [Route("{param}")] 
     [Authorize] 
     public ActionResult Index(string param = null) { 

... 

击中URL时,伟大的工程:http://example.com/account/testparam。 但是,我希望能够将值param作为可选参数。

我已经尝试将[Route("{param}")]更改为[Route("{param}*")],但从未输入Index()方法。我也尝试将其更改为[Route("{param:string=Test}")],但我得到了路由运行时错误,其中包含术语string

RoutConfig.cs包含:

public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
      routes.MapMvcAttributeRoutes(); 

      routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{param}", 
       defaults: new { controller = "Home", action = "Index", param = UrlParameter.Optional } 
      ); 
     } 

没有人有任何想法,我怎么可能会迫使Index()有使用这种替代路由语法的可选参数?这在我的应用的其他部分非常有用,所以我想保留RoutePrefixRoute装饰器。

UPDATE

我仍然在试图找出了这一点,所以我改变了我的路线装饰以[Route("{param:int=0}")]和我的构造函数public ActionResult Index(int id),它按预期工作(即http://example.com/account就会认为http://example.com/account/0被输入。这正是我想要的,只有使用string数据类型

当我改变了装饰到:[Route("{id:string=\"\"}")]和构造函数public ActionResult Index(string id),我看到了运行时错误:

The inline constraint resolver of type 'DefaultInlineConstraintResolver' was unable to resolve the following inline constraint: 'string'.

回答

6

找到了答案here。我需要使用?可以空param

[Route("{param?}")] 
[Authorize] 
public ActionResult Index(string param = null) { 
    ... 
} 

希望这将有助于未来的人。 关于这个话题我找不到很多参考文献。

6

@ Brett's答案很好:将?添加到Route属性中的参数中,然后在Action签名中提供一个默认值允许该参数是可选的。

这里有一篇来自Mike Wasson的优秀文章,文章内容为Attribute Routing in Web API 2,其中包含一些关于可选参数的文章。

迈克也即将应用多个约束会谈,并说:

You can apply multiple constraints to a parameter, separated by a colon.

[Route("users/{id:int:min(1)}")] 
    public User GetUserById(int id) { ... } 

,直到你想多约束可选参数也伟大工程......。

正如我们所知,应用?允许参数是可选的。因此,采取上述的例子,人们可能会认为

[Route("users/{id:int?:min(1)}")] 
public User GetUserById(int id = 1) { ... } 

约束id参数为大于0的整数,或为空(在这种情况下为1的缺省使用)。在现实中,我们得到的错误信息:

The inline constraint resolver of type 'DefaultInlineConstraintResolver' was unable to resolve the following inline constraint: 'int?'.

事实证明,在秩序的约束事宜!只需把可选的约束?毕竟其他方面的限制给出的预期行为

[Route("users/{id:min(1):int?}")] 
public User GetUserById(int id = 1) { ... } 

这适用于超过2个约束为好,例如

[Route("users/{id:min(1):max(10):int?}")] 
public User GetUserById(int id = 1) { ... } 
+1

有关提示的提示。 – Nicholi 2016-02-29 23:11:43