Unescape JavaScript的escape()使用C#

时间:2010-09-23 12:06:23

标签: c# javascript asp.net

C#中的任何函数是否像JavaScript一样处理escape / unescape?

我有一个像这样的JSON字符串:

{"Feeds":[{"Url":"www.test.com","FeedType":"Twitter"},{"Url":"www.test2.com","FeedType":"Youtube"}]}

escape()

之后看起来像这样

%7B%22Feeds%22%3A%5B%7B%22Url%22%3A%22www.test.com%22%2C%22FeedType%22%3A%22Twitter%22%7D%2C%7B%22Url%22%3A%22www.test2.com%22%2C%22FeedType%22%3A%22Youtube%22%7D%5D%7D

在我的C#代码中,我想取消对此字符串的看法,使其看起来与escape()

之前完全相同

这可能吗?

7 个答案:

答案 0 :(得分:65)

HttpUtility.UrlDecode应该可以做到这一点。

答案 1 :(得分:16)

escape()相当于

HttpUtility.UrlDecode(str, System.Text.Encoding.Default);

默认情况下,UrlDecode使用UTF8而escape()则不使用。

答案 2 :(得分:11)

这是我发现使用这些内容的最佳方式:

在C#中编码:

System.Uri.EscapeDataString("<string>");

在JavaScript中解码:

decodeURI("<string>");

在JavaScript中编码:

encodeURI("<string>");

用C#解码:

System.Uri.UnescapeDataString("<string>");

更新2016年1月27日:刚刚找到了一个更兼容的方法,它还使用javascript对URI协议(http://)进行编码:

在JavaScript中编码:

encodeURIComponent("<string>");

在JavaScript中解码:

decodeURIComponent("<string>");

答案 3 :(得分:5)

噢,伙计,为什么我们有时会过分思考这些东西。 当API函数变得愚蠢时,请向库开发人员发送一个karma cuss,然后解决它......

HttpUtility.UrlEncode(editext, System.Text.Encoding.Default).Replace("+","%20");

答案 4 :(得分:2)

    internal static string UnJavascriptEscape(string s)
    {
        // undo the effects of JavaScript's escape function
        return HttpUtility.UrlDecode(s.Replace("+", "%2b"), Encoding.Default);
    }

答案 5 :(得分:1)

为了使用HttpUtility而不必引用System.Web,请尝试以下方法:

Str = Str.Replace("+", " ");
Str = Regex.Replace(Str, "%([A-Fa-f\\d]{2})", a => "" + Convert.ToChar(Convert.ToInt32(a.Groups[1].Value, 16)));

另外,当我尝试使用HttpUtility.UrlDecode时,它不适用于特殊字符áéíóúñ。

答案 6 :(得分:0)

我花了8个小时试图

HttpUtility.UrlDecode 

工作,放弃并使用

HttpUtility.HtmlDecode

立即起作用。

相关问题