首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从c#中的字符串中提取基本URl?

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

Stack Overflow用户
提问于 2013-03-27 00:05:20
回答 3查看 46.2K关注 0票数 36

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

谢谢

EN

回答 3

Stack Overflow用户

发布于 2013-03-27 00:08:39

代码语言:javascript
复制
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/
票数 5
EN

Stack Overflow用户

发布于 2017-10-23 22:29:34

只需为Uri类创建一个扩展。在我看来,从一开始就应该有的东西。它会让你的生活变得更轻松。

代码语言:javascript
复制
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;
    }
 }

用法:

代码语言:javascript
复制
//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();
票数 1
EN

Stack Overflow用户

发布于 2013-03-27 00:20:55

如果你想把这3个都放在一个列表中,你也可以从这里开始。一旦你得到了Host Name,你可以做很多的事情。如果你想要得到.com之外的所有东西,使用AbsolutePath方法

代码语言:javascript
复制
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);
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15641797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档