Search code examples
c#.neturluri

Changing the scheme of System.Uri


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

var uri = new Uri("http://localhost/hello")

and I need to change it to 'https'. My issue is in limited UriBuilder ctors and Uri.Port defaulting to 80 (should we change it to 443? hardcoding?). The code must respect all Uri properties such as possible basic auth credentials, query string, etc.


Solution

  • Ended up with this one:

    var uriBuilder = new UriBuilder(requestUrl)
    {
        Scheme = Uri.UriSchemeHttps,
        Port = -1 // default port for scheme
    };
    
    var uri = uriBuilder.Uri;