3

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.

Phillip Davis
  • 315
  • 3
  • 15

1 Answers1

2

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.

Todd Menier
  • 37,557
  • 17
  • 150
  • 173
  • 1
    You do have an excellent point, and I'll have to say you did give the right answer to my question. But I literally changed my actual attribute name `[DataMember(Name="key")]` to `JsonProperty` to make the question easier and attract a bigger audience. I've added a message on the Flurl github and see if this is their intended functionality. Thanks for the help. – Phillip Davis Jan 31 '19 at 19:34
  • :) And I just now realized who you were Todd, thanks a ton for an absolutely fantastic product. – Phillip Davis Jan 31 '19 at 19:57
  • Yeah, "they" is mostly me. :) Thanks for the kind words. Feel free to open a suggestion related to this, it's been brought up at least once before and I might consider something for a future release. – Todd Menier Jan 31 '19 at 22:52