Home > Net >  HttpClient decoding my encoded URI causes request to fail
HttpClient decoding my encoded URI causes request to fail

Time:01-25

HttpClient seems to not respect encoded strings.

var id = Uri.EscapeDataString("\"MyId\"");
var uri = new Uri($@"https://www.example.com/{id}").AbsoluteUri;
var req = new HttpRequestMessage(HttpMethod.Post, uri);

My uri object contains https://www.example.com/"MyId" which is correct.

Inspecting req.RequestUri shows the correct value for every property except for LocalPath, everything else seems to have the correct " encoded quote.

I then send the request:

await httpClient.SendAsync(req)

and it makes a request to https://www.example.com/"MyId" (no longer encoded?) and the request fails.

uri.UserEscaped shows false after creating. I tried to escape the entire URI using Uri.EscapeUriString, but that function is deprecated and suggests using Uri.EscapeDataString for the query (which I'm already doing).


I followed the solution from the GitHub issue in this question, however it did not fix my issue (using AbsoluteUri).

This question is incorrect as it is not just the ToString() method, the actual request includes the decoded values.

This question is just a dead link.


How can I actually send my request with the encoded " quote values?

CodePudding user response:

Don't do that Uri.EscapeDataString, just include the id as-is in the Uri.

var id = "\"MyId\"";
var uri = new Uri($@"https://www.example.com/{id}").AbsoluteUri;
var req = new HttpRequestMessage(HttpMethod.Post, uri);

Fiddler shows below request was made.

POST https://www.example.com/"MyId"

CodePudding user response:

you can use them (namespace System.Web)

HttpUtility.UrlDecode("")
HttpUtility.UrlEncode("")
  • Related