Programing

Uri에서 호스트 교체

lottogame 2020. 10. 14. 07:20
반응형

Uri에서 호스트 교체


.NET을 사용하여 Uri의 호스트 부분을 대체하는 가장 좋은 방법은 무엇입니까?

즉 :

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는별로 도움이되지 않는 것 같습니다.


System.UriBuilder 는 당신이 추구 하는 것입니다 ...

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

@Ishmael이 말했듯이 System.UriBuilder를 사용할 수 있습니다. 예를 들면 다음과 같습니다.

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

참고 URL : https://stackoverflow.com/questions/479799/replace-host-in-uri

반응형