I have a string with me and I want to call a rest method from that string. Can anyone think of a better approach then the one I described below for converting str to Rest Call Url.
str : https://P1.P2.com/ProjectName/_build?definitionId=123
Extract P1 and ProjectName and definitionId
Rest Call : https://dev.azure.com/P1/ProjectName/_apis/pipelines/123/runs?api-version=6.0-preview.1
Here, after getting the string, split it with "//" and then split array[1] with "/" and then get P1, ProjectName and then find something with "=" and then the number ?
Not sure if this might be ok.
Update : I can get this as a URI. But how to convert it then ?
CodePudding user response:
First off, use Uri
to parse out the host, path, and query parts of the URI:
var uri = new Uri("https://P1.P2.com/ProjectName/_build?definitionId=123");
For extracting P1
from the host, it's probably going to be easiest to split on .
:
string subdomain = uri.Host.Split('.')[0]
For ProjectName
, just look at uri.Segments
:
string projectName = uri.Segments[1];
For definitionId
, parse the query string with HttpUtility.ParseQueryString
:
var query = HttpUtility.ParseQueryString(uri.Query);
string definitionId = query["definitionId"];
To construct the new Uri, use a UriBuilder
:
var builder = new UriBuilder()
{
Scheme = "https",
Host = "dev.azure.com",
Path = $"{subdomain}/{projectName}_apis/pipelines/{definitionId}/runs",
Query = "api-version=6.0-preview.1",
};
string result = builder.ToString();