Search code examples
c#httpclient.net-6.0

HttpClient will Encode the url internally


Here is my link:

58.87.64.22/?{{%25}}cake\=1

When I open it in Chrome, it will give me 400 status code which is correct.

But When I open it using HTTP client, it will return 200 status code:

HttpClient client = new HttpClient();
var w = await client.GetAsync("http://58.87.64.22/?{{%25}}cake\\=1");

it seems HTTP client will encode the URL into this:

58.87.64.22/?%7B%7B%25%7D%7Dcake%5C=1

when I test the encoded URL in Chrome, it will open a webpage and will return 200 status code.

How to solve such a thing? I need to get 400 status code when sending request to this URL.


Solution

  • Pass a Uri object instantiated via the overload having a UriCreationOptions argument with DangerousDisablePathAndQueryCanonicalization set to true.

    Gets or sets a value that indicates whether the path and query are validated and normalized.
    true to disable path and query validation; false to enable it.

    var options = new UriCreationOptions 
    {
        DangerousDisablePathAndQueryCanonicalization = true
    };
    var uri = new Uri(@"http://58.87.64.22/?{{%25}}cake\=1", options);
    
    HttpClient client = new HttpClient();
    await client.GetAsync(uri);
    

    Fiddler shows that below request is being made without any encoding.

    GET http://58.87.64.22/?{{%25}}cake\=1 HTTP/1.1
    Host: 58.87.64.22
    

    Resulting in a Bad Request HTTP status code.

    HTTP/1.1 400