20

What's the most efficient way to get a specific parameter from a relative URL string using C#?

For example, how would you get the value of the ACTION parameter from the following relative URL string:

string url = "/page/example?ACTION=data&FOO=test";

I have already tried using:

var myUri = new Uri(url, UriKind.Relative);
String action = HttpUtility.ParseQueryString(myUri.Query).Get("ACTION");

However, I get the following error:

This operation is not supported for a relative URI.

3
  • 1
    Have you tried Request.QueryString["ACTION"]? Commented Jul 28, 2016 at 19:36
  • 1
    If you're using asp.net, use the QueryString property on HttpRequest. Commented Jul 28, 2016 at 19:36
  • 2
    the URL string is coming from a database, not from the browser, so I don't think using HttpRequest would work? Commented Jul 28, 2016 at 19:38

3 Answers 3

20
 int idx = url.IndexOf('?');
 string query = idx >= 0 ? url.Substring(idx) : "";
 HttpUtility.ParseQueryString(query).Get("ACTION");
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, using the IndexOf and Substring worked. I haven't tried it with URIBuilder yet.
Second solution to use UriBuilder does NOT work for relative paths. It expects constructor parameter URL to have host. UriBuilder help
12

While many of the URI operations are unavailable for UriKind.Relative (for whatever reason), you can build a fully qualified URI through one of the overloads that takes in a Base URI

Here's an example from the docs on Uri.Query:

Uri baseUri = new Uri ("http://www.contoso.com/");
Uri myUri = new Uri (baseUri, "catalog/shownew.htm?date=today");

Console.WriteLine(myUri.Query); // date=today

You can also get the current base from HttpContext.Current.Request.Url or even just create a mock URI base with "http://localhost" if all you care about is the path components.

So either of the following approaches should also return the QueryString from a relative path:

var path = "catalog/shownew.htm?date=today"
var query1 = new Uri(HttpContext.Current.Request.Url, path).Query;
var query2 = new Uri(new Uri("http://localhost"), path).Query;

Comments

4

You can get the query through UriBuilder. This does require the removal of the forward slash from the beginning of the Uri. The query can then be passed to HttpUtility.ParseQueryString to get the desired parameter:

var query = new System.UriBuilder("page/example?ACTION=data&FOO=test").Query;
var parameter = System.Web.HttpUtility.ParseQueryString(query)["ACTION"]; //data

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.