Alex Rivera | Logout

System.Net.Uri with urlencoded characters

Asked 2010-02-23T18:02:53.477
13

I need to request the following URL inside my application:

http://feedbooks.com/type/Crime%2FMystery/books/top

When I run the following code:

Uri myUri = new Uri("http://feedbooks.com/type/Crime%2FMystery/books/top");

The Uri constructor decodes the %2F into a literal /, and I get a 404 error because it has changed the URL to:

http://feedbooks.com/type/Crime/Mystery/books/top

The Uri class has a constructor that takes a parameter dontEscape, but that constructor is deprecated and setting it to true has no effect.

My first thought was to do something like:

Uri myUri = new Uri("http://feedbooks.com/type/Crime%252FMystery/books/top");

With the hopes that it would convert %25 into a literal %, but that didn't work either.

Any ideas how to create a correct Uri object for this particular URL in .NET?

Edit
Report

1 Answer

8

It's a bit easier in .NET 4.0. You can put a setting in your config file like this:

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

It only works for the 'http' and 'https' schemes.

Or here's a new version of the LeaveDotsAndSlashesEscaped method. It doesn't need a particular Uri instance, just call it when your application starts up:

private void LeaveDotsAndSlashesEscaped()
{
    var getSyntaxMethod = 
        typeof (UriParser).GetMethod("GetSyntax", BindingFlags.Static | BindingFlags.NonPublic);
    if (getSyntaxMethod == null)
    {
        throw new MissingMethodException("UriParser", "GetSyntax");
    }

    var uriParser = getSyntaxMethod.Invoke(null, new object[] { "http" });

    var setUpdatableFlagsMethod = 
        uriParser.GetType().GetMethod("SetUpdatableFlags", BindingFlags.Instance | BindingFlags.NonPublic);
    if (setUpdatableFlagsMethod == null)
    {
        throw new MissingMethodException("UriParser", "SetUpdatableFlags");
    }

    setUpdatableFlagsMethod.Invoke(uriParser, new object[] {0});
}
answered 2011-08-26T09:19:16.157

Your Answer