HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Truncate port number from absolute Uri

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
urinumberabsolutetruncateportfrom

Problem

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?

Solution

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 && 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

Code Snippets

Uri oldUri = new Uri("http://myhost:443/Home/Index");
UriBuilder builder = new UriBuilder(oldUri);
builder.Port = -1;
Uri newUri = builder.Uri;
static Uri RemovePortIfDefault(Uri uri) {
    if (uri.IsDefaultPort && uri.Port != -1) {
        UriBuilder builder = new UriBuilder(uri);
        builder.Port = -1;
        return builder.Uri;
    }
    else return uri;
}

Context

StackExchange Code Review Q#25485, answer score: 15

Revisions (0)

No revisions yet.