简体   繁体   中英

How to set a query string value in C# relative urls

Assume there is a relative URL like: /api/services or /api/services?id=4 . What is the best practice to add another query string parameter to the specified URL. For example, adding type=1 should lead to the following results: /api/services?type=1 and /api/services?id=4&type-1 . The type of the URLs is general, and any part of the standard URI format may exist.

Note that the standard System.Uri and System.UriBuilder classes have limited capability for relative URIs.

Add nuget package Microsoft.AspNetCore.WebUtilities .

namespace so74768078
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var test1 = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString("/api/services", "type", "1");
            var test2 = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString("/api/services?id=4", "type", "1");

            Console.WriteLine(test1);
            Console.WriteLine(test2);
        }
    }
}

console output

/api/services?type=1
/api/services?id=4&type=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM