Getting error 400 / 404 - HttpUtility.UrlEncode not encoding full string?

前端 未结 1 1377
迷失自我
迷失自我 2021-02-15 17:25

Why do the following URLs give me the IIS errors below:

A) http://192.168.1.96/cms/View.aspx/Show/Small+test\'

A2) http://192.168.1.96/cms/View.aspx/Show/Small%2

1条回答
  •  臣服心动
    2021-02-15 17:50

    OK, answering my own question... hate doing it but I got the answer after much digging.

    http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/04/27/asp-net-400-bad-request-with-restricted-characters.aspx

    The long and short of it is the Microsoft in all its glory decided not to stick to a international standard, again.

    %, &, *, or : can not be in a URL, encoded or decoded before a ? for any reason.

    To get around this I've written my own encode and decode:

    static public string UrlEncode(string encode)
    {
        if (encode == null) return null;
        string encoded = "";
    
        foreach (char c in encode)
        {
            int val = (int)c;
            if (val == 32 || val == 45 || (val >= 48 && val <= 57) || (val >= 65 && val <= 90) || (val >= 97 && val <= 122))
                encoded += c;
            else
                encoded += "%" + val.ToString("X");
        }
    
        // Fix MS BS
        encoded = encoded.Replace("%25", "-25").Replace("%2A", "-2A").Replace("%26", "-26").Replace("%3A", "-3A");
    
        return encoded;
    }
    
    static public string UrlDecode(string decode)
    {
        if (decode == null) return null;
        // Fix MS BS
        decode = decode.Replace("-25", "%25").Replace("-2A", "%2A").Replace("-26", "%26").Replace("-3A", "%3A");
    
        return HttpUtility.UrlDecode(decode);
    }
    

    Neither of the functions are Unicode friendly at the moment, but for now it works.

    0 讨论(0)
提交回复
热议问题