Search code examples
c#asp.net-mvc-3attributerouting

Route ambiguity in AttributeRouting


I'm trying to create two different routes on two different action methods like this:

[GET("/project/create")]
public ActionResult Create()

[GET("/project/{projectId}")]
public ActionResult Details(int projectId)

The problem is that when i navigate to /project/create, I'm routed to the Details page, which fails because projectId is not an int.

I realise that I could change the Details route to something like /project/{projectId}/details but I would like for it to work the other way.

Also a solution could be to make projectId a string, and internally redirect to the Create action if projectId == "create" but that would feel awful.

I am using AttributeRouting for this.


Solution

  • If you're using v2.2 or later of attribute routing, you can simply specify a constraint on the project id:

    [GET("/project/{projectId:int}")]
    

    And if pre v2.2 you can use a regex to the same effect:

    [GET("/project/{projectId(^[\\d]+$)}")]
    

    However in the more general case you can specify the precedence of the routes within a controller by setting the Precedence property of the attribute:

    [GET("/project/create", Precedence = 1)]
    public ActionResult Create()
    
    [GET("/project/{projectId}", Precedence = 2)]
    public ActionResult Details(int projectId)