简体   繁体   中英

Extract base URl from a string in c#?

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 " http://www.example.edu/mypage/default.aspx " or " http://www.example.eu/mypage/default.aspx ". How can I extract the base URl from this kind of a string.

Thanks

You can use URI class to get the host name.

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

Edit You can use uri.Scheme and uri.Port to get the .Scheme eg (http, ftp) and .Port to get the port number like (8080)

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

You can use Uri.GetLeftPart to get the base URL.

The GetLeftPart method returns a string containing the leftmost portion of the URI string, ending with the portion specified by part.

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

The following examples show a URI and the results of calling GetLeftPart with Scheme, Authority, Path, or Query, MSDN . 在此输入图像描述

Short Answer

myUri.GetLeftPart(System.UriPartial.Authority)

Long Answer
Assuming "Base URI" means something like http://www.example.com , you can get the base uri like this:

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

This gives: http://www.example.com

Note: uri.Host gives: www.example.com (not including port or scheme)

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/

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

If you want to get all 3 of them in a list here is something you could also start with there are so many options you can do once you get the Host Name also if you are wanting everything past the .com use the AbsolutePath method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM