1

I have an application where uses post comments. Security is not an issue. string url = http://example.com/xyz/xyz.html?userid=xyz&comment=Comment

What i want is to extract the userid and comment from above string. I tried and found that i can use IndexOf and Substring to get the desired code BUT what if the userid or comment also has = symbol and & symbol then my IndexOf will return number and my Substring will be wrong. Can you please find me a more suitable way of extracting userid and comment. Thanks.

2
  • No. You can get them from the Response object, I believe, as query string values. Commented Jun 5, 2015 at 14:46
  • possible duplicate of Get url parameters from a string in .NET Commented Jun 5, 2015 at 14:50

2 Answers 2

5

I got url using string url = HttpContext.Current.Request.Url.AbsoluteUri;

Do not use AbsoluteUri property , it will give you a string Uri, instead use the Url property directly like:

var result = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);

and then you can extract each parameter like:

Console.WriteLine(result["userid"]);
Console.WriteLine(result["comment"]);

For other cases when you have string uri then do not use string operations, instead use Uri class.

Uri uri = new Uri(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment");

You can also use TryCreate method which doesn't throw exception in case of invalid Uri.

Uri uri;
if (!Uri.TryCreate(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment", UriKind.RelativeOrAbsolute, out uri))
{
    //Invalid Uri
}

and then you can use System.Web.HttpUtility.ParseQueryString to get query string parameters:

 var result = System.Web.HttpUtility.ParseQueryString(uri.Query);
Sign up to request clarification or add additional context in comments.

8 Comments

I am newbie, can you please suggest how can i extract xyz and Comment from the above link after using uri
I got url using string url = HttpContext.Current.Request.Url.AbsoluteUri; Now i do Uri uri = new Uri(@url); var result = System.Web.HttpUtility.ParseQueryString(uri.Query);
Remember that IndexOf is always there when you need it.
@Asbat, thats great, do not use AbsoluteUri, instead use Url directly, without converting it to string.
@Asbat, I have modified the answer
|
0

The ugliest way is the following:

String url = "http://example.com/xyz/xyz.html?userid=xyz&comment=Comment";
usr = url.Split('?')[1];
usr= usr.Split('&')[0];
usr = usr.Split('=')[1];

But @habib version is better

2 Comments

But as my question say, it will fail I assume if user id or comment contain ? & =
That will be an invalid url then

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.