April 18, 2020

How to build query string for System.Net.HttpClient GET Request

In this post I will explain multiple ways to use parameters for HTTP GET Request using System.Net.HttpClient. You don't need to build parameters string by concatenating different values from a name-value collection.

  • First method is to use HttpUtility.ParseQueryString() function.

    var query = HttpUtility.ParseQueryString(string.Empty);
    query["p1"] = "value1";
    query["p2"] = "value2";
    string queryString = query.ToString();
      

    queryString variable contains the parameters in query string format.

  • Another way could be to use UriBuilder class.

    var builder = new UriBuilder("http://example.com");
    builder.Port = -1;
    
    var query = HttpUtility.ParseQueryString(builder.Query);
    query["p1"] = "value1";
    query["p2"] = "value2";
    builder.Query = query.ToString();
    
    string url = builder.ToString();
      

    The url variable will contain both the page URL and query string parameters.

  • If you do not want to include a reference to System.Web in your project, you can use FormDataCollection class by adding reference to System.Net.Http.Formatting.

    var parameters = new Dictionary()
    {
     { "p1", "value1" },
     { "p2", "value2 + SomeOtherValue?" },
    }; 
    
    var queryString = new FormDataCollection(parameters).ReadAsNameValueCollection().ToString();
      

    queryString variable now contains the parameters in query string format.

  • If you are using ASP.Net Core, you can use the QueryHelpers class by first adding reference to Microsoft.AspNetCore.WebUtilities.

    var query = new Dictionary
    {
     ["p1"] = "value1",
     ["p2"] = "value2",
    };
    
    var response = await client.GetAsync(QueryHelpers.AddQueryString("/api/", query));
      

No comments:

Post a Comment