Home > Back-end >  Best way to format a query string for tracking
Best way to format a query string for tracking

Time:10-13

I am looking for an opinion.

I have some data in an excel which is converted into a Base64 string. This Base64 string is being sent appended to an URL i.e. https://my.site.com/q=Base64

Is this the correct way to do this? The Base64 string contains user information.

I have noted that when we do as above some characters are lost/ replaced hence I have trouble finding the tracking code in the database.

Any guidance will be most helpful.

Most of my code is C# and jQuery

CodePudding user response:

A potential problem could be that base64 strings can contain the , = and / characters, which are not URL friendly and could change the meaning of your data. In order to fix that, you have to encode your URL. .NET provides a HttpUtility class that contains methods for encoding and decoding URLs.

A quick example that demonstrates how it could be done:

private static string AddArgumentsToUrl(string url, IDictionary<string, string>? queryParameters)
{
    queryParameters ??= new Dictionary<string, string>();
    string argumentsString = string.Join("&", queryParameters.Select(arg => $"{arg.Key}={arg.Value}"));
    return !string.IsNullOrEmpty(argumentsString) ? $"{url}?{argumentsString}" : url;
}

public static string Base64Encode(string plainText)
{
    var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
    return Convert.ToBase64String(plainTextBytes);
}

And you could call it like this:

var baseUrl = "https://my.site.com/";
var queryParams = new Dictionary<string, string>
{
    { "q", $"{HttpUtility.UrlEncode(Base64Encode("test"))}" }
};
var res = AddArgumentsToUrl(baseUrl, queryParams); // https://my.site.com/?q=dGVzdA==

Lastly, be sure to decode the URL on the receiving side and then decode the base64 to plain text.

  • Related