Phillip Davis
Phillip Davis

Reputation: 325

Flurl's PostUrlEncodedAsync is ignoring JsonProperty names

I'm using Flurl (one of my favorite APIs) to now post form-data to a url. I'm quite familiar using 'JsonProperty' attributes to name the keys, and use standard casing for c#.

But when I use PostUrlEncodedAsync, the normal JsonProperty code doesn't convert to 'key', but remains 'KeyName' and the call fails.

public class TokenTest
{
    [JsonProperty("key")]
    public string KeyName { get; set; }
}

So I'm a little baffled that this doesn't work right out of the box.

var request = new TokenTest
{
   KeyName = "ewr1-QuQ5jo88WfCpNPz2kTb8ES",
};

var result = await url.PostUrlEncodedAsync(request).ReceiveString();

My call fails since it wants 'key', but I'm sending 'KeyName'. JsonProperty/DataMember attributes have always worked in the past, so why is it failing here?


As I work on the problem, it seems to stem from the fact that this method calls DefaultUrlEncodedSerializer to do the serialization. This serializer ignores the JsonProperty names.

   var urlEncodedContent = new CapturedUrlEncodedContent(request.Settings.UrlEncodedSerializer.Serialize(token));
   var jsonEncodedContent = new CapturedUrlEncodedContent(request.Settings.JsonSerializer.Serialize(token));

For example, the jsonEncodedContent uses the JsonProperty attribute, while the urlEncodedContent ignores the attribute.

Upvotes: 3

Views: 1185

Answers (1)

Todd Menier
Todd Menier

Reputation: 39319

JsonProperty, as the name implies, is related to JSON serialization. It's actually a Json.NET feature; the fact that it works with Flurl is just a convenient consequence of the fact that Flurl uses Json.NET in its default JSON serializer. But I don't think it's reasonable to expect something called JsonProperty to work with URL-encoding, because URL-encoding has nothing to do with JSON.

You can work around this pretty easily by just projecting onto an anonymous object:

url.PostUrlEncodedAsync(new { key = token.KeyName });

Not as clean or type-safe, but I've always found this to be acceptable since URL-encoded data tends to be smaller/flatter/simpler than JSON payloads, on average.

Upvotes: 2

Related Questions