Url Encode Forward Slash (/) in .NET

How can I get Uri or HttpWebRequest to allow uri containing both / and %2f as shown below?

 http://localhost:55672/api/exchanges/%2f/MyExchange 

I tried this ...

 WebRequest request = HttpWebRequest.Create("http://localhost:55672/api/exchanges/%2f/MyExchange"); 

... and this...

 Uri uri = new Uri("http://localhost:55672/api/exchanges/%2f/MyExchange", true); WebRequest request = HttpWebRequest.Create(uri); 

... and this...

 UriBuilder builder = new UriBuilder(); builder.Port = 55672; builder.Path = "api/exchanges/%2f/MyExchange"; WebRequest request = HttpWebRequest.Create(builder.Uri); 

However, with all these parameters, request.RequestUri ends with http://localhost:55672/api/exchanges///MyExchange , and request.GetResponse() http://localhost:55672/api/exchanges///MyExchange 404 response.

FYI I'm trying to use the RabbitMQ HTTP API, and typing Url in Chrome gives the expected JSON result.

+6
source share
4 answers

We had the same problem and found that this problem exists if you target the .NET 4.0 platform. It goes away if you are targeting the .NET 4.5 platform. Therefore, if this is an option for you, switch the target infrastructure and it should solve your problem.

+5
source

I had the same issue when communicating with the RabbitMQ management API some time ago. I wrote a blog post about this, including a couple of solutions:

http://mikehadlow.blogspot.co.uk/2011/08/how-to-stop-systemuri-un-escaping.html

You can disable the behavior either with some unpleasant reflection in the System.Uri code, or using the parameter in App.config (or Web.config):

 <uri> <schemeSettings> <add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" /> </schemeSettings> </uri> 
+3
source

Use Server.Encode code for the part containing reserved characters. http://msdn.microsoft.com/en-us/library/ms525738(v=vs.90).aspx

+1
source

Please use Server.UrlEncode, the server side is required or an alternative will be System.Uri.EscapeDataString

+1
source

Source: https://habr.com/ru/post/920457/


All Articles