Asked by:
How to Dynamically Append to a Base URL using HttpClient

Question
-
User1503905807 posted
Is it possible to dynamically append to an URL from SQL query results using HttpClient class in C#?
I inherited an ASP.Net webapp that I need to updated
I have a base URL like – https://SomeSite.com/api/
Now I need to add {ServerName=”server-name; Location=”location”; Owner=”owner”} to that URL and then execute that link.
The server name, location and owner data is coming from a SQL Server DB. I need to query the DB and populate the URL from the results and I need to loop that task based on the number of rows in the query results.
So the URL should look like - http://SomeSite.com/api/{ServerName=MyServer; Location=MyLocation; Owner=Me}
I’ve been unable to find any examples on how to append to the URL.
Thanks in advance!
Friday, August 21, 2020 8:09 PM
All replies
-
User-474980206 posted
See the query string property.
https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.querystring?view=netstandard-2.0
Saturday, August 22, 2020 3:10 PM -
User1686398519 posted
Hi ronniej962,
You can use the UriBuilder.Query property to set any query information contained in the URI.
I wrote a simple example, you can refer to it.
Model
public class testdata1 { public string ServerName { get; set; } public string Location { get; set; } public string Owner { get; set; } }
Index
public async Task<ActionResult> Index() { //Assuming that data has been queried from the database
//I assumed some data. List<testdata1> testlist = new List<testdata1>(); for(int i =0; i < 2; i++) { testlist.Add(new testdata1 { ServerName = "server"+i, Location = "location"+i, Owner = "owner"+i }); } for (int i = 0; i < testlist.Count; i++) { UriBuilder baseUri = new UriBuilder("https://localhost:44307/api/Values/test1"); //Create query string //Use the UriBuilder.Query property to get or set all the query information contained in the URI. string queryToAppend = "ServerName=" + testlist[i].ServerName + "&Location=" + testlist[i].Location + "&Owner=" + testlist[i].Owner; if (baseUri.Query != null && baseUri.Query.Length > 1) { baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend; } else { baseUri.Query = queryToAppend; } var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync(baseUri.ToString()); if (response.IsSuccessStatusCode) { } } return View(); }test1
[HttpGet] public string test1(string ServerName,string Location,string Owner) { return "test1"; }
Here is the result.
Best Regards,
YihuiSun
Monday, August 24, 2020 6:28 AM -
User1503905807 posted
Thank you YihuiSun!!!
I will give this a try and follow up!!!
Monday, August 24, 2020 2:18 PM