Search code examples
c#urlencode

UTF-8 URL Encode


I am having issues in encoding my query params using HttpUtility.UrlEncode() it is not getting converted to UTF-8.

 query["agent"] = HttpUtility.UrlEncode("{\"mbox\":\"mailto: [email protected]\"}");

I tried using the overload method and passed utf encoding but still it is not working.

expected result:

?agent=%7B%22mbox%22%3A%22mailto%3AUserName%40company.com%22%7D

Actual Result:

?agent=%257b%2522mbox%2522%253a%2522mailto%253aUserName%2540company.com%2522%257d

     public StatementService(HttpClient client, IConfiguration conf)
    {
        configuration = conf;
        var BaseAddress = "https://someurl.com/statements?";             
        client.BaseAddress = new Uri(BaseAddress);
        client.DefaultRequestHeaders.Add("Custom-Header", 
                                          "customheadervalue");
        Client = client;
    }

   public async Task<Object> GetStatements(){
     var query = HttpUtility.ParseQueryString(Client.BaseAddress.Query);
     query["agent"] = HttpUtility.UrlEncode( "{\"mbox\":\"mailto:[email protected]\"}");

        var longuri = new Uri(Client.BaseAddress + query.ToString());
        
        var response = await Client.GetAsync(longuri);
        response.EnsureSuccessStatusCode();

        using var responseStream = await response.Content.ReadAsStreamAsync();

        dynamic statement = JsonSerializer.DeserializeAsync<object>(responseStream);
 //Convert stream reader to string 
        StreamReader JsonStream = new StreamReader(statement);
        string JsonString = JsonStream.ReadToEnd();
        //convert Json String to Object.
        JObject JsonLinq = JObject.Parse(JsonString);
        // Linq to Json
        dynamic res = JsonLinq["statements"][0].Select(res => res).FirstOrDefault();
        return await res;

}


Solution

  • The method HttpUtility.ParseQueryString internally returns a HttpValueCollection. HttpValueCollection.ToString() already performs url encoding, so you don't need to do that yourself. If you do it yourself, it is performed twice and you get the wrong result that you see.

    I don't see the relation to UTF-8. The value you use ({"mbox":"mailto: [email protected]"}) doesn't contain any characters that would look different in UTF-8.

    References: