0

Let's say for example that I have 2 controllers with respective attributes

[Route("a/b")]

and

[Route("a/{str}")]

Then there's a conflict if the request to URL "a/b" is made. Is there a way I can write a unit test that looks for such conflicts?

Ms. Corlib
  • 4,993
  • 4
  • 12
  • 19
  • 1
    Try to do something like [Testing Routes In ASP.NET MVC](http://haacked.com/archive/2007/12/17/testing-routes-in-asp.net-mvc.aspx/) – Artavazd Balayan Jul 19 '16 at 18:24

1 Answers1

1

There is no such thing as a "conflicting" route. In routing, the first match wins, and the rest will be ignored.

When using Route attributes, you need to be especially aware of this behavior because .NET attributes don't guarantee any order. Therefore, when you have routes that are similar such as this, you should use the Order property of the attribute to ensure the most specific route is executed first. Order is processed from lowest to highest number.

[Route("a/b", Order = 1)]
[Route("a/{str}", Order = 2)]

Of course, this only comes into play when the routes are similar to each other and you have one with a placeholder. But you should always be aware when you add a route with a placeholder that it could be registered before any similar routes without a placeholder (even worse, the behavior could change from one compile of the application to the next), so you must set the order when using placeholders.

Since route order is significant, it is quite easy to add a route in the wrong place that renders other routes inoperable. You should set up route unit testing not only to ensure the routing works, but also to make sure your routes continue to work as you add more. This will give you the "detection" that you are looking for, but as I previously mentioned you may get false positives by using this approach because the order of your attributes could change from one compile to the next without the Order property in place.

The safest way is to be vigilant about using the Order property when you have placeholders.

Additional Info:

NOTE: Convention-based routing doesn't change order from one compile to the next the way attribute routing does. If you want tight control over the order of your routes, use convention-based routing instead.

Community
  • 1
  • 1
NightOwl888
  • 55,572
  • 24
  • 139
  • 212