Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url Encode Forward Slash (/) in .NET

Tags:

c#

url

rabbitmq

How can I force either Uri or HttpWebRequest 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 up http://localhost:55672/api/exchanges///MyExchange and request.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.

like image 683
Clay Avatar asked Jul 13 '12 20:07

Clay


1 Answers

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>
like image 142
Mike Hadlow Avatar answered Oct 11 '22 20:10

Mike Hadlow