I need to get version no part from a url. Url will look like this "http://myweb.com/api/v1/customer". I need to get the "1" value from the url. How can i do this?
Thanks in advance
I need to get version no part from a url. Url will look like this "http://myweb.com/api/v1/customer". I need to get the "1" value from the url. How can i do this?
Thanks in advance
You can use the Uri class, which has a built in parser specifically for parsing uris, and exposes a nice API for examining the components of the URI.
Uri uri = new UriBuilder("http://myweb.com/api/v1/customer").Uri;
string versionString = uri.Segments[2]; // v1/
You can, of course, further process this to extract just the number, as shown in the next snippet. The benefit is that you won't have to worry about complicated edge cases in parsing URIs with your regex.
int version = int.Parse(Regex.Match(versionString, @"\d+").Value);
Here is a demonstration: http://ideone.com/4kgey7
\d+ would return any number not only the one next to /vv1/ segment of the URI, we can use a naive regex like \d+ against the extracted URI segment. If you've spotted a case where this code works incorrectly, please fork the demo and change the string to demonstrate the problem.You could use lookaround assertions like below,
Regex.Match(yourstring, @"(?<=/v)\d+(?=/)").Value;
(?<=/v) Positive lookbehind asserts that the match must be preceded by /v\d+ Matches one or more digits.(?=/) Positive lookahead asserts that the match must be followed by a forward-slash / character.If you are using MVC you can use attribute routing:
[GET("api/v{version:int}/customer")]
public ActionResult GetCustomer(int version) {
...
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
api/v(.+)/regex will capture version in group\1