Search code examples
c#asp.neturiasp.net-4.8

C# Create URI from string without decoding %2F as a forward slash


Given the following string URI

var str = "https://www.google.com/maps/search/C%2F-%20GBI%20Logistics%2C%2078%20Mallard%20Way%20(Door%20%232)%2C%20CANNINGTON%2C%20WA%2C%206107";

How can I create a URI from this string which doesn't decode the %2F as a forward slash / ??

when evaluating new Uri(str).ToString(); the result is

https://www.google.com/maps/search/C/- GBI Logistics, 78 Mallard Way (Door %232), CANNINGTON, WA, 6107

which is not intended (unescaping the forward slash changes the path of the URI). The correct result should be:

https://www.google.com/maps/search/C%2F- GBI Logistics, 78 Mallard Way (Door %232), CANNINGTON, WA, 6107

I also tried using the new Uri(uriString, dontEscape) overload, but as specified in the documentation this overload is obsolete and the dontEscape paramater is always made to be false.

My (test) runtime environment is

Framework Description: .NET Framework 4.8.9139.0
OS Description: Microsoft Windows 10.0.22621 
OS Architecture: X64
Process Architecture: X64
CLR Version: 4.0.30319.42000
Language Version: 4.0

Which is output from the following commands

System.Diagnostics.Debug.WriteLine("  Framework Description: " + System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
System.Diagnostics.Debug.WriteLine("  OS Description: " + System.Runtime.InteropServices.RuntimeInformation.OSDescription);
System.Diagnostics.Debug.WriteLine("  OS Architecture: " + System.Runtime.InteropServices.RuntimeInformation.OSArchitecture);
System.Diagnostics.Debug.WriteLine("  Process Architecture: " + System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture);
System.Diagnostics.Debug.WriteLine("  CLR Version: " + System.Environment.Version.ToString());
System.Diagnostics.Debug.WriteLine("  Language Version: " + System.Environment.Version.Major + "." + System.Environment.Version.Minor);

I'm using classic ASP.NET Web API Project (not .Core)


Solution

  • Mike Hadlow's answer from https://stackoverflow.com/a/17830750/4910205 worked for me. Note that i had to copy and add the https scheme as well as per below

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

    Although it doesn't sit well with me to modify the behaviour specifically for ASP.NET for something that shoudld be framework-agnostic!