Truncate port number from absolute Uri We had a requirement to remove the port number from the Request.Url.AbsoluteUr i.e

Actual:


  https://mysitename:443/Home/Index


Expected:


  https://mysitename/Home/Index


The code I used for this is

 string newUrl = context.Request.Url.AbsoluteUri.Replace(":" + context.Request.Url.Port, string.Empty);


This is working fine. but I'm eager to know is there any better way to do this?
Use UriBuilder and set Port to -1

Uri oldUri = new Uri("http://myhost:443/Home/Index");
UriBuilder builder = new UriBuilder(oldUri);
builder.Port = -1;
Uri newUri = builder.Uri;


In case you want to remove the port part only when it is default, e.g. 80 for http and 443 for https, use snippet below (credit goes to Chris for the idea)

static Uri RemovePortIfDefault(Uri uri) {
    if (uri.IsDefaultPort &amp;&amp; uri.Port != -1) {
        UriBuilder builder = new UriBuilder(uri);
        builder.Port = -1;
        return builder.Uri;
    }
    else return uri;
}



  If the Port property is set to a value of -1, this indicates that the default port value for the protocol scheme will be used to connect to the host.


See: UriBuilder.Port Property