Learning
Learning

Reputation: 20001

Querystring return null when using & instead of & from URL

I am using following function to get value of query string from a a URL

contact.aspx?PID=15&Lang=en-US --- Works

contact.aspx?PID=15&Lang=en-US --- Fails

if (!string.IsNullOrEmpty(Helper.GetQueryStringValue("Lang")))
{
  //Do somthing
}


public static String GetQueryStringValue(String qValue)
{
  String value = String.Empty;
    if (HttpContext.Current.Request.QueryString[qValue] != null)
    {
      value = HttpContext.Current.Request.QueryString[qValue].ToString();
    }
 return value;
}

when i use & in url it return null value for querystring Lang and when i use& it works.

I am not able to understand why this happens

Upvotes: 0

Views: 2048

Answers (3)

Dave Mroz
Dave Mroz

Reputation: 1489

It has nothing do to with encoding or decoding.

The ampersand is the delimiter for the query string arguments, so what you actually have in your URL is two names: PID and amp;Lang If you change your code to look for the latter, you'll get en-us as your output.

Response.Write(GetQueryStringValue("amp;Lang"));

Decoding the URL wont work because it hasn't been properly encoded to begin with. The properly encoded URL would be:

contact.aspx?PID%3d15%26amp%3bLang%3den-US 

If you had that you could decode it, but it still wouldn't get you what you're looking for because you still don't have an name called Lang; even after decoding it's still amp;Lang

Also, this is totally unrelated, but the ToString() is redundant in the GetQueryStringValue function. That line can simply be:

value = HttpContext.Current.Request.QueryString[qValue];

Upvotes: 2

Yves Schelpe
Yves Schelpe

Reputation: 3463

This is because & is actually interpreted as the character '&' and not the concatenator.. The query string provided is just not valid.

You could try to decode/parse it with Server.UrlDecode(queryString). And you could try replacing all & to '%26' and then feeding it into Server.UrlDecode - but it's not guaranteed that that will solve the problem. For more info on Server.UrlDecode see MSDN page http://msdn.microsoft.com/en-us/library/6196h3wt(v=vs.110).aspx -

Bottom line is that the queryString is malformed at the moment. If you have control over the code to render the url, then always use & and not &. (Example: https://stackoverflow.com/a/829138/1155847)

Upvotes: 0

xspydr
xspydr

Reputation: 3050

You need to decode the url prior to attempting to access query string variables...

Server.UrlDecode(HttpContext.Current.Request.QueryString[qValue])

Checkout MSDN http://msdn.microsoft.com/en-us/library/6196h3wt%28v=vs.110%29.aspx

Upvotes: -1

Related Questions