Url Encode Forward Slash (/) in .NET
Solution 1
We just had the same problem and discovered that this problem exists if you are targeting the .NET 4.0 framework. It goes away if you target the .NET 4.5 framework. So if that's an option for you, switch your target framework and it should resolve your issue.
Solution 2
I had this exact same problem when communicating with the RabbitMQ management API a while back. I wrote a blog post about it, including a couple of solutions:
http://mikehadlow.blogspot.co.uk/2011/08/how-to-stop-systemuri-un-escaping.html
You can turn the behavior off either with some nasty reflection into the System.Uri code, or by a setting in App.config (or Web.config):
<uri>
<schemeSettings>
<add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
</schemeSettings>
</uri>
Solution 3
Please use Server.UrlEncode it is required server side or the alternate will be System.Uri.EscapeDataString
Solution 4
Use Server.Encode for part containing the reserved characters. http://msdn.microsoft.com/en-us/library/ms525738(v=vs.90).aspx
Related videos on Youtube
Clay
Updated on September 15, 2022Comments
-
Clay over 1 year
How can I force either
Uri
orHttpWebRequest
to allow a uri containing both/
and%2f
like the following?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 of these,
request.RequestUri
ends uphttp://localhost:55672/api/exchanges///MyExchange
andrequest.GetResponse()
produces a 404 response.FYI I'm trying to use RabbitMQ's HTTP API and typing the Url in Chrome produces the expected JSON result.
-
Clay almost 12 yearsUnfortunately Uri.EscapeDataString produces the same result:
request = HttpWebRequest.Create("http://localhost:55672/api/exchanges/" + Uri.EscapeDataString("/") + "/MyExchange");
-
Clay over 10 yearsPerhaps I'm doing something wrong, but neither solution seems to work from VS 2010 or 2012 (using console application).
Uri uri = new Uri("http://localhost:55672/api/exchanges/%2f/MyExchange"); Console.WriteLine(uri);
-
Mike Hadlow over 10 yearsI use exactly that method in my RabbitMQ.Management.Client library. Have a look here: github.com/mikehadlow/EasyNetQ/tree/master/Source/…
-
Clay over 10 yearsTargeting .NET 4.5 fixed it, even without the uri config setting. Perhaps it was a bug in the .NET framework.
-
X3074861X over 5 yearsSeems to be back in .NET Core 2.0.