2

I'm using HttpClient (Dot Net 5) and I'm trying to get an entity from a DotNetCore web service by specifying it's id in the URL.

  • It works if the id does not contain any characters that need encoding.
  • It fails (HTTP 404) if the id contains a slash (/).
    • Web service diagnostics confirm that the request does not reach the method.

Other clients such as Postman or Swagger work fine.

Example of failing:

string id = "Person/65-C";
var httpResponse = await httpClient.GetAsync(string.Format("/persons/{0}", System.Web.HttpUtility.UrlEncode(id)));
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Chris Fellows
  • 149
  • 1
  • 5
  • 3
    Have you tried not URL encoding it? .NET might be doing that automatically for you, and so your string gets double-escaped. – Noah Jul 21 '21 at 16:16
  • Can you also please share the code for the webservice part? – Kit Jul 23 '21 at 21:45
  • @HereticMonkey Sorry and thank you for you comment. I deleted my answer since it doesn't give a clear solution. – Mohamed AMAZIRH Jul 24 '21 at 09:16
  • @Chris Fellows, I tried but couldn't reproduce the problem on my machine with a simple web api and simple console program. Can you please share more information about your setup : which webserver are you using (kestrel or iis). Also are you using a reverse proxy in front the webserver (like nginx or apache). If yes, did your tests with Postman use the reverse proxy url or the webserver url? (I'm asking this because nginx can be configured to decode paths before passing them to the webserver). – Mohamed AMAZIRH Jul 24 '21 at 09:18
  • @Chris Fellows, also can you please run this code to get the actual url used to call the webservice `var actualUri = (await client.GetAsync(string.Format("/persons/{0}", System.Web.HttpUtility.UrlEncode("Person/65-C")))).RequestMessage.RequestUri.AbsoluteUri;`. Once you have the value of `actualUri`, can you compare it to what's displayed on Swagger in the **Curl** section. You can also just use **Curl** directly to test the response of the server : `curl -X GET "${value of actualUri here}" -H "accept: text/plain"` – Mohamed AMAZIRH Jul 24 '21 at 09:42

2 Answers2

1

I ran into the same problem. Spent ours to find a solution without any luck. I ended up changing my route and converting my route parameter to QueryString parameter instead. May not be an ideal solution for every scenario, but worked in my case.

Changed the route from

$"api/album/{HttpUtility.UrlEncode("a/b")}"

to

$"api/album/url=a/b"

And in controller

[HttpGet]
public TestModel Get([FromQuery] string url)
{
}
Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48
0

I suggest you should use [HttpGet("persons/{**value}")] attribute in your server api.

My test sample code.

[HttpGet("persons/{**value}")]
public string test(string value)
{
    return "userid: = " + value;
}

enter image description here

enter image description here

enter image description here

Jason Pan
  • 15,263
  • 1
  • 14
  • 29