Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UriBuilder - remove port

Tags:

c#

I want to build a Uri based off some string values, but I'd like to avoid showing the port when I call .ToString().

var uriBuilder = new UriBuilder("http://www.google.co.uk/")
{
    Path = "test"
};

The below code outputs http://www.google.co.uk:80/test instead of http://www.google.co.uk/test. Is there a way to not include the port in the final string or do I have to use one of the workarounds (such as new Uri(new Uri(baseUrl), relativePath) instead?

like image 691
TheDoomDestroyer Avatar asked Dec 14 '25 06:12

TheDoomDestroyer


2 Answers

To achieve the result that you require you can just do like this.

var uriBuilder = new UriBuilder()
{
    Scheme = "http",
    Host = "www.google.co.uk",
    Path = "test"
};

Uri uri = uriBuilder.Uri;

In the uri you will have the 'http://www.google.co.uk/test' result that you want.

If you check on Microsoft docs you can see that

This constructor initializes a new instance of the UriBuilder class with the Fragment, Host, Path, Port, Query, Scheme, and Uri properties set as specified in uri. If uri does not specify a scheme, the scheme defaults to "http:".

like image 60
Magfa Avatar answered Dec 15 '25 18:12

Magfa


As documented here, set the Port to -1 and it will not print.

var uriBuilder = new UriBuilder("http://www.google.co.uk/")
{
    Path = "test",
    Port = -1
};
like image 33
Hugh W Avatar answered Dec 15 '25 20:12

Hugh W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!