Sostituisci host in Uri


88

Qual è il modo migliore per sostituire la parte host di un Uri utilizzando .NET?

Cioè:

string ReplaceHost(string original, string newHostName);
//...
string s = ReplaceHost("http://oldhostname/index.html", "newhostname");
Assert.AreEqual("http://newhostname/index.html", s);
//...
string s = ReplaceHost("http://user:pass@oldhostname/index.html", "newhostname");
Assert.AreEqual("http://user:pass@newhostname/index.html", s);
//...
string s = ReplaceHost("ftp://user:pass@oldhostname", "newhostname");
Assert.AreEqual("ftp://user:pass@newhostname", s);
//etc.

System.Uri non sembra aiutare molto.

Risposte:


149

System.UriBuilder è quello che stai cercando ...

string ReplaceHost(string original, string newHostName) {
    var builder = new UriBuilder(original);
    builder.Host = newHostName;
    return builder.Uri.ToString();
}

1
Avrei consigliato la classe Uri, ma mi sarei sbagliato. Buona risposta.
Jonathan C Dickinson,

Funziona alla grande, tieni presente che se leggi la proprietà Query, è preceduta da un? E se imposti la proprietà Query con una stringa che inizia con?, Un'altra? sarà anteposto.
Dave

Dovrai gestire le porte, se sono specificate in originale o nuovo.
Realtà soggettiva

43

Come dice @Ishmael, puoi usare System.UriBuilder. Ecco un esempio:

// 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;

3
Ho il sospetto che potrebbe essere meglio ottenere l' Uriistanza chiamando newUriBuilder.Uripiuttosto che formattandola e analizzandola.
Sam

@ Sam hai ragione, la Uriproprietà è un'opzione molto migliore. Grazie. Aggiornato.
Drew Noakes

Attento alla .Urichiamata. Se hai qualcosa in quello UriBuilderche non si traduce in un Uri valido, verrà lanciato. Quindi, ad esempio, se hai bisogno di un host con caratteri jolly *, puoi impostarlo .Host, ma se lo chiami .Uriverrà generato. Se lo chiami UriBuilder.ToString(), restituirà l'Uri con il carattere jolly al suo posto.
CubanX
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.