HttpWebRequest to URL with dot at the end

Workaround in workaround tab at the official bug report:

https://connect.microsoft.com/VisualStudio/feedback/details/386695/system-uri-incorrectly-strips-trailing-dots?wa=wsignin1.0#tabs

.. seems to be valid. Basically, run this code to reset a static flag in .NET before working with System.Uri:

MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (getSyntax != null && flagsField != null)
{
    foreach (string scheme in new[] { "http", "https" })
    {
        UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { scheme });
        if (parser != null)
        {
            int flagsValue = (int)flagsField.GetValue(parser);
            // Clear the CanonicalizeAsFilePath attribute
            if ((flagsValue & 0x1000000) != 0)
                flagsField.SetValue(parser, flagsValue & ~0x1000000);
        }
    }
}

Demonstrated:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var surl = "http://x/y./z";

            var url = new Uri(surl);
            Console.WriteLine("Broken: " + url.ToString());

            MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            if (getSyntax != null && flagsField != null)
            {
                foreach (string scheme in new[] { "http", "https" })
                {
                    UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { scheme });
                    if (parser != null)
                    {
                        int flagsValue = (int)flagsField.GetValue(parser);
                        // Clear the CanonicalizeAsFilePath attribute
                        if ((flagsValue & 0x1000000) != 0)
                            flagsField.SetValue(parser, flagsValue & ~0x1000000);
                    }
                }
            }

            url = new Uri(surl);
            Console.WriteLine("Fixed: " + url.ToString());

            Console.WriteLine("Press ENTER to exit ...");
            Console.ReadLine();
        }
    }
}

Leave a Comment