Home > Mobile >  QueryBuilder is not encoding `@` in query parameters, anyway to force it?
QueryBuilder is not encoding `@` in query parameters, anyway to force it?

Time:12-15

I have a custom web service that I query and provide an email ([email protected]) and ad account (MyDomain\\MyUser) as arguments using QueryBuilder, but when I do .ToQueryString(), the @ symbol is not encoded?

Is there a way to get a properly encoded string or a reason it's not encoding?

QueryBuilder qb = new QueryBuilder();
qb.Add("adAccount", "MyDomain\\MyUser");
qb.Add("email", "[email protected]");

var queryString = qb.ToQueryString();

My code above returns (@):

?adAccount=MyDomain\MyUser&[email protected]

But I would expect (@):

?adAccount=MyDomain\MyUser&[email protected]

CodePudding user response:

QueryBuilder's source code is located here - it's not a complicated class, basically just a List<KeyValuePair<string,string>> that performs an UrlEncode on the key/values when it's being ToString'd. It's not sealed and the ToString is overridable so you can create your own version that will work anywhere a QueryBuilder is expected:

class QueryBuilderEx : QueryBuilder
{
    public override string ToString()
    {
        return base.ToString().Replace("@", "@");
    }
}

If you only want to edit the value, and leave the key alone it's a bit more of a nuisance, because you need to reimplement the ToString in the style of the original, but the _params list in which the pairs are stored is private so not accessible to your subclass. You can however, have your QueryBuilder enumerate itself:

class QueryBuilderEx : QueryBuilder
{
    public override string ToString()
    {
        var builder = new StringBuilder();
        bool first = true;
        foreach(var pair in this)
        {
            builder.Append(first ? '?' : '&');
            first = false;
            builder.Append(UrlEncoder.Default.Encode(pair.Key));
            builder.Append('=');
            builder.Append(UrlEncoder.Default.Encode(pair.Value).Replace("@", "@"));
        }

        return builder.ToString();
    }
}
  • Related