Home > Software engineering >  .NET Httpclient encoding a url but I dont want it to
.NET Httpclient encoding a url but I dont want it to

Time:12-23

I have a url with the pipe | symbol. When I call it from Httpclient it is getting encoded to |.

I read there was a 'dont escape' on the Uri in .NET but that has now been marked obsolete.

Is there anything I can do so that this | is not encoded on the request?

CodePudding user response:

Maybe this is an interesting post that might help: URL Encoding using C#

Personally, I am using a library like RestSharp to do this.

I am not sure where that pipe needs to be. In the URL segment or query? I assume the query parameters in the following example since that is the only place where I could imagine you need a pipe.

using var client = new RestClient("https://example.com/api");

var request = new RestRequest("your/endpoint");

// the last parameter encode=false will disable encoding
request.AddQueryParameter("queryname", "term|otherterm", false); 

var response = await client.GetAsync(request);

// GET https://example.com/api/your/endpoint?queryname=term|otherterm

CodePudding user response:

The | character is a reserved character in URLs and must be percent-encoded when used in the query string or fragment identifier of a URL. This is done to ensure that the URL is properly interpreted by the server and by clients.

However, if you need to include the | character in your URL and you do not want it to be encoded, you can use the Uri.EscapeDataString method to encode the entire URL except for the | character. Here is an example of how you could do this:

string url = "https://example.com/api/search?q=term|otherterm";
string encodedUrl = url.Replace("|", Uri.EscapeDataString("|"));

using (HttpClient client = new HttpClient())
{
    HttpResponseMessage response = await client.GetAsync(encodedUrl);
    // process the response
}

This will encode all reserved characters in the URL except for the | character, which will be sent to the server as

  • Related