use a query parameter in csharp

In C#, you can use query parameters to pass information through URLs. Here is an example:

main.cs
string url = "https://example.com/api/data?id=123";
string id = "unknown";

if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
    string query = uri.Query;
    if (!string.IsNullOrEmpty(query))
    {
        NameValueCollection queryParams = HttpUtility.ParseQueryString(query);
        id = queryParams["id"];
    }
}

Console.WriteLine($"ID: {id}");
359 chars
15 lines

This code takes a URL that contains a query parameter (id=123). It uses the Uri class to parse the URL and get the query string. The HttpUtility.ParseQueryString method then converts the query string into a collection of key-value pairs, which you can access like a dictionary. In this example, we are accessing the value of the "id" parameter and assigning it to a variable named id.

Note that you'll need to include the following namespace at the top of your file to use HttpUtility.ParseQueryString:

main.cs
using System.Collections.Specialized;
using System.Web;
56 chars
3 lines

gistlibby LogSnag