tags:

views:

89

answers:

3

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?

+2  A: 

This is a bug I filed a while back. It's supposed to be fixed in 4.0, but I'm not holding my breath. Apparently it's still a problem in the RC.

David Morton
Ah. Do you know of any workaround for a 3.5 deployment?
Matt Bridges
Sorry, but I haven't found any workaround for this yet. It's a bad one. Go vote it up.
David Morton
A: 

hi, is this bug has fixed in .net 4.0?

wingoo
+1  A: 

I ran into the same problem using 2.0...

I discovered a workaround posted at this blog:

// System.UriSyntaxFlags is internal, so let's duplicate the flag privately
private const int UnEscapeDotsAndSlashes = 0x2000000;

public static void LeaveDotsAndSlashesEscaped(Uri uri)
{
    if (uri == null)
    {
        throw new ArgumentNullException("uri");
    }

    FieldInfo fieldInfo = uri.GetType().GetField("m_Syntax", BindingFlags.Instance | BindingFlags.NonPublic);
    if (fieldInfo == null)
    {
        throw new MissingFieldException("'m_Syntax' field not found");
    }
    object uriParser = fieldInfo.GetValue(uri);

    fieldInfo = typeof(UriParser).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
    if (fieldInfo == null)
    {
        throw new MissingFieldException("'m_Flags' field not found");
    }
    object uriSyntaxFlags = fieldInfo.GetValue(uriParser);

    // Clear the flag that we don't want
    uriSyntaxFlags = (int)uriSyntaxFlags & ~UnEscapeDotsAndSlashes;

    fieldInfo.SetValue(uriParser, uriSyntaxFlags);
}

It works perfectly.

Hope this helps (better late than never!)

Chase B. Gale
Awesome! Stackoverflow never ceases to amaze me.
Matt Bridges
Glad I could help...
Chase B. Gale