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.
Ended up with this one:
Another iteration on Nick Evans answer:
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 becomehttps://localhost:12345/hello
instead ofhttps://localhost/hello
.Here's how to do that easily:
Note that we have to read
uri.Uri.IsDefaultPort
before settinguri.Scheme
.Here is a working example: https://dotnetfiddle.net/pDrF7s
Another iteration on Good Night Nerd Pride's answer, as an extension:
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.
Usage: