Changing the scheme of System.Uri

UserControl picture UserControl · Jul 31, 2013 · Viewed 20.5k times · Source

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.

Answer

UserControl picture UserControl · Jul 31, 2013

Ended up with this one:

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