简体   繁体   中英

What's the difference between new Uri(..) and new UriBuilder(..).Uri for the same host?

In a web application, I have an audienceURI used for the authentication. When I set it from code like the following:

var audience1 = new UriBuilder("dev.website.com")
                 {
                    Port = 443,
                    Scheme = "https",
                    Path = "/"
                 }.Uri; // Does not work!

It is not wokring.

But when I set it like this:

var audenice2 = new Uri("https://dev.website.com"); // It works!

it works fine.

The funny thing is that the following is working fine !!

var audience3 = new Uri(audience1.ToString());  // It works!

Any idea what's the difference?

The UriBuilder (like any implementation of the builder pattern) allows you to provide the pieces needed to assemble a larger object in 'piecemeal' fashion, and then allowing you to generate an instance of the final product (using the .Uri property). You don't necessarily need to build the object in one go (ie you can mutate a builder as you go along).

However, it seems you aren't using the UriBuilder(String) constructor correctly. From MSDN

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.

Meaning you would need to do this to use this constructor overload:

 var audience1 = new UriBuilder("https://dev.website.com").Uri;

(or even https://dev.website.com:443 )

Which wouldn't be useful to you as it has no benefit over constructing a Uri directly with the same string.

The UriBuilder would more typically be used to piece-meal assemble the Uri, like so:

var myUriBuilder = new UriBuilder();
myUriBuilder.Host = (host == "dev")
  ? "dev.website.com"
  : "qa.website.com";

 if (useSsl)
 {
     myUriBuilder.Scheme = "https";
     myUriBuilder.Port = 443;
 }

var myUri = myUriBuilder.Uri;

(ie with somewhat complex logic determining the fate of each of the builder's properties in separate statements).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM