jakejgordon
jakejgordon

Reputation: 4098

Can you use a regex in .NET WebApi Route URI For API Versioning

In MVC and WebApi you can add parameter constraints to your routes (see http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints). You can even use regular expressions for the parameter constraints. However, I'm wondering if it's possible to use regular expressions to handle API versioning where many routes could/should route to the same action.

For example, I'm trying to version my API in the actual URI like this:

/api/v3/SomeResource

Where v3 indicates that it's version 3 of the API. If I'm on version 3 of my API it is likely that many of the actions have been unchanged throughout all three versions and would hence need to respond to:

/api/v1/SomeResource
/api/v2/SomeResource
/api/v3/SomeResource

Therefore, I would like to just be able to put a regex in my route attribute like this: [Route("api/v(1|2|3)/SomeResource")] but it appears as though it doesn't treat the v(1|2|3) as a regex and instead treats it as a literal. In other words, a request to /api/v1/SomeResource isn't going to this action.

Is it possible to accomplish what I'm trying to accomplish? is there a way to put a regex in my route?

Thanks in advance!

Upvotes: 2

Views: 7679

Answers (2)

Eric Gurney
Eric Gurney

Reputation: 263

Take a look at this: [HttpGet, Route("Api/v{version:int:regex(1|2|3)}/SomeResource")]

Reference: http://sampathloku.blogspot.com/2013/12/attribute-routing-with-aspnet-mvc-5.html

Upvotes: 5

NightOwl888
NightOwl888

Reputation: 56909

No, it is not possible. Per MSDN.

A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL which are delimited by the slash (/) character.

Nor is it particularly useful in this case, because you would typically route each API version to a separate controller. Therefore, each version would require a separate route, not a single route that matches all versions.

The document which you have already linked has a section that specifically covers API versioning (although it doesn't provide much detail).

Upvotes: 1

Related Questions