How can I parse HTTP urls in C#?

25,152

Solution 1

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;

Solution 2

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.

Share:
25,152
vijay053
Author by

vijay053

Updated on November 28, 2020

Comments

  • vijay053
    vijay053 over 3 years

    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. Can you suggest some other efficient approch?

    Urls are like these:

    • server/func1
    • server/func1/SubFunc1
    • server/func1/SubFunc2
    • server/func2/SubFunc1
    • server/func2/SubFunc2