解码Url与特殊&查询参数值中的“+”字符

Decode Url with special & or + characters in query parameters value

本文关键字:字符 参数 Url 查询 解码      更新时间:2023-09-26

我在解码带有参数的Base64编码URL时遇到了这个困难

eg: http://www.example.com/Movements.aspx?fno=hello&vol=Bits & Pieces

我的预期结果应该是:Fno = hellovol = Bits &作品

#Encoding:
//JAVASCRIPT                
var base64 = $.base64.encode("&fno=hello&vol=Bits & Pieces");
window.location.replace("Movements.aspx?" + base64);
#Decoding c#
string decodedUrl = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(Request.Url.Query.Replace("?", ""))); // Replace is used to remove the ? part from the query string. 
string fileno = HttpUtility.ParseQueryString(decodedUrl).Get("fno");
string vol = HttpUtility.ParseQueryString(decodedUrl).Get("vol");
实际结果:

Fno = hellovol = Bits

我已经搜索stackoverlow,似乎我需要添加一个自定义算法来解析解码的字符串。但由于实际的URL比这个例子中显示的要复杂得多,我建议最好向专家寻求替代解决方案!

感谢阅读!

您的querystring需要正确编码。Base64不是正确的方法。使用encodeURIComponent代替。您应该分别对每个值进行编码(尽管在示例的大多数部分中不需要):

var qs = "&" + encodeURIComponent("fno") + "=" + encodeURIComponent("hello") + "&" + encodeURIComponent("vol") + "=" + encodeURIComponent("Bits & Pieces");
// Result: "&fno=hello&vol=Bits%20%26%20Pieces"

那么你就不需要在c#中进行Base64解码了。

var qs = HttpUtility.ParseQueryString(Request.Url.Query.Replace("?", ""));
var fileno = qs.Get("fno");
var vol = sq.Get("vol");

如果URL被正确编码,您将有:

http://www.example.com/Movements.aspx?fno=hello&卷= + % 26 +星星点点

%26是&
的url编码字符。空格将被+

取代

在JS中,使用escape来正确编码你的url!

[编辑]

使用encodeURIComponent而不是escape,因为正如Sani Huttunen所说,'escape'已弃用。对不起!