Replace host in Uri

前端 未结 2 1295
北荒
北荒 2020-12-03 06:44

What is the nicest way of replacing the host-part of an Uri using .NET?

I.e.:

string ReplaceHost(string original, string newHostName);
//...
string s         


        
相关标签:
2条回答
  • 2020-12-03 06:57

    As @Ishmael says, you can use System.UriBuilder. Here's an example:

    // the URI for which you want to change the host name
    var oldUri = Request.Url;
    
    // create a new UriBuilder, which copies all fragments of the source URI
    var newUriBuilder = new UriBuilder(oldUri);
    
    // set the new host (you can set other properties too)
    newUriBuilder.Host = "newhost.com";
    
    // get a Uri instance from the UriBuilder
    var newUri = newUriBuilder.Uri;
    
    0 讨论(0)
  • 2020-12-03 07:02

    System.UriBuilder is what you are after...

    string ReplaceHost(string original, string newHostName) {
        var builder = new UriBuilder(original);
        builder.Host = newHostName;
        return builder.Uri.ToString();
    }
    
    0 讨论(0)
提交回复
热议问题