7

i have an ashx file that requires some query-string values to deliver appropriate images.

The problem is some search engines urlencode then htmlencode those urls in their cache or when they index those.

So for example instead of getting

/preview.ashx?file=abcd.jpg&root=small

i get

/preview.ashx?file=abcd.jpg&root=small

this basically throws off the context.Request.QueryString["root"] so it thinks that there's no variable root

i guess the second key in the querystring is amp;root i.e the part after the & sign.

What i'm wondering is if there's a way to automatically html and urldecode the querystring on serverside so that the program doesn't get confused.

3
  • You tagged the question with C - did you mean C#? Commented Sep 7, 2012 at 20:12
  • Shouldn't that be: context.Request.QueryString["root"] (the string root) Commented Sep 7, 2012 at 20:13
  • yes.. i meant c#... context.Request.QueryString["root"] should return small but it returns null because there's no such key as root.... there's a key amp;root Commented Sep 7, 2012 at 20:38

3 Answers 3

14

There is no harm in calling HttpUtility.HtmlDecode or HttpUtility.UrlDecode more than once.

string queryString = "/preview.ashx?file=abcd.jpg&root=small";
var parsedString = HttpUtility.HtmlDecode(queryString);
var root = HttpUtility.ParseQueryString(parsedString)["root"];
Sign up to request clarification or add additional context in comments.

3 Comments

thanks... i actually was trying to avoid doing it that way... but i guess since there's no way to SET context.Request.QueryString after decoding it, that should work too. Was wondering if there was a way to decode it serverside so that i could leave the program out of it
Actually, wouldn't it be a problem if you had an encoded + sign in your original URL and you called decode twice? The first time, it would be decoded to +, but the second time, + would be decoded as a space. Unless I'm missing something?
@rar How about posting an example using for ex HttpUtility.UrlEncode and HttpUtility.UrlDecode so that we can talk on a concrete sample code.
11

To URL encode and decode you can use the following methods:

string encoded = System.Web.HttpUtility.UrlEncode(url);

string decoded = System.Web.HttpUtility.UrlDecode(url);

I've seen instances in the past where the Query String has been doubly encoded. In which case you'll need to doubly decode — this may be your issue...

Comments

1

WebUtility.UrlDecode(countyName)

Latest in .net core 6

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.