Changing the scheme of System.Uri

后端 未结 4 1456
逝去的感伤
逝去的感伤 2020-12-30 19:02

I\'m looking for canonical way of changing scheme of a given System.Uri instance with System.UriBuilder without crappy string manipulations and magic constants. Say I have

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 19:24

    UserControl's answer works fine unless you have to make sure non-default ports are preserved in the URI.

    For instance, http://localhost:12345/hello should become https://localhost:12345/hello instead of https://localhost/hello.

    Here's how to do that easily:

    public static string ForceHttps(string requestUrl)
    {
        var uri = new UriBuilder(requestUrl);
    
        var hadDefaultPort = uri.Uri.IsDefaultPort;
        uri.Scheme = Uri.UriSchemeHttps;
        uri.Port = hadDefaultPort ? -1 : uri.Port;
    
        return uri.ToString();
    }
    

    Note that we have to read uri.Uri.IsDefaultPort before setting uri.Scheme.

    Here is a working example: https://dotnetfiddle.net/pDrF7s

提交回复
热议问题