How can I parse HTTP urls in C#?

前端 未结 3 1622
小蘑菇
小蘑菇 2020-12-01 16:50

My requirement is to parse Http Urls and call functions accordingly. In my current implementation, I am using nested if-else statement which i think is not an optimized way.

相关标签:
3条回答
  • 2020-12-01 17:22

    I combined the split in Suncat2000's answer with string splitting to get at interesting features of the URL. I am passing in a full Uri including https: etc. from another page as the navigation argument e.Parameter:

    Uri playlistUri = (Uri)e.Parameter;
    string youtubePlaylistUnParsed = playlistUri.Query;
    char delimiterChar = '=';
    string[] sections = youtubePlaylistUnParsed.Split(delimiterChar);
    string YoutubePlaylist = sections[1];
    

    This gets me the playlist in the PLs__ etc. form for use in the Google APIs.

    0 讨论(0)
  • 2020-12-01 17:23

    This might come as a bit of a late answer but I found myself recently trying to parse some URLs and I went along using a combination of Uri and System.Web.HttpUtility as seen here, my URLs were like http://one-domain.com/some/segments/{param1}?param2=x.... so this is what I did:

    var uri = new Uri(myUrl);
    string param1 = uri.Segments.Last();
    
    var parameters = HttpUtility.ParseQueryString(uri.Query);
    string param2 = parameters["param2"];
    

    note that in both cases you'll be working with strings, and be specially weary when working with segments.

    0 讨论(0)
  • 2020-12-01 17:25

    I think you can get a lot of use out of the System.Uri class. Feed it a URI and you can pull out pieces in a number of arrangements.

    Some examples:

    Uri myUri = new Uri("http://server:8080/func2/SubFunc2?query=somevalue");
    
    // Get host part (host name or address and port). Returns "server:8080".
    string hostpart = myUri.Authority;
    
    // Get path and query string parts. Returns "/func2/SubFunc2?query=somevalue".
    string pathpart = myUri.PathAndQuery;
    
    // Get path components. Trailing separators. Returns { "/", "func2/", "sunFunc2" }.
    string[] pathsegments = myUri.Segments;
    
    // Get query string. Returns "?query=somevalue".
    string querystring = myUri.Query;
    
    0 讨论(0)
提交回复
热议问题