Extract base URl from a string in c#?

前端 未结 5 2117
情书的邮戳
情书的邮戳 2021-02-03 21:31

I am currently working on a project with .NET 1.1 framework and I am stuck at this point. I have a string like \"http://www.example.com/mypage/default.aspx\" or it might be \"ht

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-03 21:50

    Just create an extension to the Uri class. In my opinion things that should be there from the start. It will make your life easier.

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

    Usage:

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

提交回复
热议问题