Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse HTTP urls in C#?

Tags:

c#

url

parsing

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
like image 237
vijay053 Avatar asked Feb 04 '13 10:02

vijay053


2 Answers

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;
like image 172
Suncat2000 Avatar answered Oct 03 '22 23:10

Suncat2000


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.

like image 38
Luiso Avatar answered Oct 04 '22 01:10

Luiso