简体   繁体   中英

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

I have met this difficulty while decoding a Base64 encoded URL with parameters

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

My expected results should be: fno = hello vol = Bits & Pieces

#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");

Actual Result: fno = hello vol = Bits

I have searched stackoverlow and seems I need to add a custom algorithm to parse the decoded string. But as the actual URL is more complicated than shown in this example I taought better asks experts for an alternative solution!

Tks for reading!

If the URL were correctly encoded, you would have :

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

%26 is the url encoded caract for &
and spaces will be replaced by +

In JS, use escape to encode correctly your url!

[EDIT]

Use encodeURIComponent instead of escape because like Sani Huttunen says, 'escape' is deprecated. Sorry!

Your querystring needs to be properly encoded. Base64 is not the correct way. Use encodeURIComponent instead. you should encode each value separately (although not needed in most parts in the example):

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

Then you don't need to Base64 decode in C#.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM