C# Query String Formating

Posted on Posted in ASP.NET, C#, Programming

Have you ever had an headache with query string, like for an example “A&B” is your value of parameter “word” in your Url call.

http://example.com/?word=A&B

But the server will parse the request as the following;

Parameter: word    value: B

Parameter: B        value: null

In which that you want it to parse as;

Parameter: word    value: A&B

The HttpUtility.UrlEncode(string str) can come in and help you with this, the method will encode your string into url encode compliant. Here maybe how you can parse the url;

string value = “A&B”;

string url = string.Format({2},

(Request.ApplicationPath == “/”) ? “” : Request.ApplicationPath,


HttpUtility.UrlEncode(value),

value);

That’s it, now that you have the correct url query string parameter value; that is

http://example.com/?word=a%26b

Then you can use the normal query string method retrieve the parameter value, and this is how you can retrieve it.

string word = Request.QueryString[“word”];

I hope this help in your dynamic web application that is compliant with search engine bots.