Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double/incomplete Parameter Url Encoding

In my web app, my parameters can contain all sorts of crazy characters (russian chars, slashes, spaces etc) and can therefor not always be represented as-is in a URL.
Sending them on their merry way will work in about 50% of the cases. Some things like spaces are already encoded somewhere (I'm guessing in the Html.BuildUrlFromExpression does). Other things though (like "/" and "*") are not.

Now I don't know what to do anymore because if I encode them myself, my encoding will get partially encoded again and end up wrong. If I don't encode them, some characters will not get through.

What I did is manually .replace() the characters I had problems with.
This is off course not a good idea.

Ideas?

--Edit--
I know there are a multitude of encoding/decoding libraries at my disposal. It just looks like the mvc framework is already trying to do it for me, but not completely.

<a href="<%=Html.BuildUrlFromExpression<SearchController>(c=>c.Search("", 1, "a \v/&irdStr*ng"))%>" title="my hat's awesome!">

will render me

<a href="/Search.mvc/en/Search/1/a%20%5Cv/&irdStr*ng" title="my hat's awesome!">

Notice how the forward slash, asterisk and ampersand are not escaped. Why are some escaped and others not? How can I now escape this properly?

Am I doing something wrong or is it the framework?

like image 822
Boris Callens Avatar asked Oct 27 '08 15:10

Boris Callens


2 Answers

Parameters should be escaped using Uri.EscapeDataString:

            string url = string.Format("http://www.foo.bar/page?name={0}&address={1}",
                Uri.EscapeDataString("adlknad /?? lkm#"),
                Uri.EscapeDataString(" qeio103 8182"));

            Console.WriteLine(url);
            Uri uri = new Uri(url);
            string[] options = uri.Query.Split('?','&');
            foreach (string option in options)
            {
                string[] parts = option.Split('=');
                if (parts.Length == 2)
                {
                    Console.WriteLine("{0} = {1}",parts[0],
                        Uri.UnescapeDataString(parts[1]));
                }
            }
like image 118
Marc Gravell Avatar answered Sep 21 '22 14:09

Marc Gravell


AS others have mentioned, if you encode your string first you aviod the issue.

The MVC Framework is encoding characters that it knows it needs to encode, but leaving those that are valid URL characters (e.g. & % ? * /). This is because these are valid URL characters, although they are special chracters in a URL that might not acheive the result you are after.

like image 38
Ady Avatar answered Sep 22 '22 14:09

Ady