我目前正在做一个使用.NET 1.1框架的项目,我被困在这一点上。我有一个类似"http://www.example.com/mypage/default.aspx“的字符串,也可能是"http://www.example.edu/mypage/default.aspx”或"http://www.example.eu/mypage/default.aspx“。如何从这种字符串中提取基本URl。
谢谢
发布于 2013-03-27 00:08:39
var builder = new UriBuilder("http://www.example.com/mypage/default.aspx");
builder.Path = String.Empty;
var baseUri = builder.Uri;
var baseUrl = baseUri.ToString();
// http://www.example.com/
发布于 2017-10-23 22:29:34
只需为Uri类创建一个扩展。在我看来,从一开始就应该有的东西。它会让你的生活变得更轻松。
public static class UriExtensions
{
public static Uri AttachParameters(this Uri uri,
NameValueCollection parameters)
{
var stringBuilder = new StringBuilder();
string str = "?";
for (int index = 0; index < parameters.Count; ++index)
{
stringBuilder.Append(str +
System.Net.WebUtility.UrlEncode(parameters.AllKeys[index]) +
"=" + System.Net.WebUtility.UrlEncode(parameters[index]));
str = "&";
}
return new Uri(uri + stringBuilder.ToString());
}
public static string GetBaseUrl(this Uri uri) {
string baseUrl = uri.Scheme + "://" + uri.Host;
return baseUrl;
}
public static string GetBaseUrl_Path(this Uri uri) {
string baseUrl = uri.Scheme + "://" + uri.Host + uri.AbsolutePath;
return baseUrl;
}
}
用法:
//url - https://example.com/api/rest/example?firstname=Linus&lastname=Trovalds
Uri myUri = new Uri("https://example.com/api/rest/example").AttachParameters(
new NameValueCollection
{
{"firstname","Linus"},
{"lastname","Trovalds"}
}
);
// https://example.com
string baseUrl = myUri.GetBaseUrl();
// https://example.com/api/rest/example
string baseUrlandPath = myUri.GetBaseUrl_Path();
发布于 2013-03-27 00:20:55
如果你想把这3个都放在一个列表中,你也可以从这里开始。一旦你得到了Host Name
,你可以做很多的事情。如果你想要得到.com
之外的所有东西,使用AbsolutePath
方法
var uriList = new List<string>()
{
"http://www.mysite.com/mypage/default.aspx",
"http://www.mysite.edu/mypage/default.aspx",
"http://www.mysite.eu/mypage/default.aspx"
};
var holdList = new List<string>();
foreach (var uriName in uriList)
{
Uri uri = new Uri(uriName);
holdList.Add(uri.Host);
}
https://stackoverflow.com/questions/15641797
复制相似问题