patterncsharpModerate
Truncate port number from absolute Uri
Viewed 0 times
urinumberabsolutetruncateportfrom
Problem
We had a requirement to remove the port number from the
Actual:
Expected:
The code I used for this is
This is working fine. but I'm eager to know is there any better way to do this?
Request.Url.AbsoluteUr i.eActual:
https://mysitename:443/Home/IndexExpected:
https://mysitename/Home/IndexThe 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
In case you want to remove the port part only when it is default, e.g. 80 for
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:
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 PropertyCode 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.