从c#中的字符串中提取基本URl?

我目前正在开发一个使用.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。

谢谢

您可以使用URI类来获取主机名。

var uri = new Uri("http://www.example.com/mypage/default.aspx"); var host = uri.Host; 

编辑您可以使用uri.Scheme和uri.Port获取.Scheme例如(http,ftp)和.Port以获取端口号,如(8080)

 string host = uri.Host; string scheme = uri.Scheme; int port = uri.Port; 

您可以使用Uri.GetLeftPart获取基本URL。

GetLeftPart方法返回一个字符串,其中包含URI字符串的最左边部分,以part指定的部分结束。

 var uri = new Uri("http://www.example.com/mypage/default.aspx"); var baseUri = uri.GetLeftPart(System.UriPartial.Authority); 

以下示例显示了URI以及使用Scheme,Authority,Path或Query, MSDN调用GetLeftPart的结果。 在此处输入图像描述

 uri.GetLeftPart(...) 

假设“基本URI”意味着像http://www.example.com ,你可以得到这样的基础uri:

 var uri = new Uri("http://www.example.com/mypage/default.aspx"); var baseUri = uri.GetLeftPart(System.UriPartial.Authority) 

这给出了: http://www.example.comhttp://www.example.com

注意: uri.Host给出: www.example.com (不包括端口或方案)

 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/ 

只需创建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(); 

如果你想在列表中获取它们中的所有3个,那么你也可以从一开始就有很多选项,如果你想要通过.com使用AbsolutePath方法,你也可以获得Host Name

 var uriList = new List() { "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(); foreach (var uriName in uriList) { Uri uri = new Uri(uriName); holdList.Add(uri.Host); }