Changing the scheme of System.Uri

后端 未结 4 1427
逝去的感伤
逝去的感伤 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:29

    I prefer to pass the desired https port number into the ForceHttps method if you want to use a custom one otherwise omit the https port or use -1 to use the standard one (implicitly). I don't really bother with the port that is already on the url because http and https can never use the same port on the same server.

    In the event that the url is already https, it will pass through unchanged leaving whatever port is there in place.

    private static string ForceHttps(string requestUrl, int? httpsPort = null)
    {
        var uri = new UriBuilder(requestUrl);
        // Handle https: let the httpsPort value override existing port if specified
        if (uri.Uri.Scheme.Equals(Uri.UriSchemeHttps)) {
            if (httpsPort.HasValue)
                uri.Port = httpsPort.Value;
            return uri.Uri.AbsoluteUri;
        }
    
        // Handle http: override the scheme and use either the specified https port or the default https port
        uri.Scheme = Uri.UriSchemeHttps;
        uri.Port = httpsPort.HasValue ? httpsPort.Value : -1;
    
        return uri.Uri.AbsoluteUri;
    }
    

    Usage:

    ForceHttps("http://www.google.com/"); // https://www.google.com/
    ForceHttps("http://www.google.com/", 225); // https://www.google.com:225/
    ForceHttps("http://www.google.com/", 443); // https://www.google.com:443/
    ForceHttps("https://www.google.com/"); // https://www.google.com/
    ForceHttps("https://www.google.com:443/"); // https://www.google.com:443/
    ForceHttps("https://www.google.com:443/", -1); // https://www.google.com/
    ForceHttps("http://www.google.com:80/"); // https://www.google.com/
    ForceHttps("http://www.google.com:3000/", 8080); // https://www.google.com:8080/
    

提交回复
热议问题