Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostAsJsonAsync ignoring JsonProperty name attribute

I have a static method that posts data as follows:

public static Task<HttpResponseMessage> PostExAsync<TValue>(this HttpClient client, string path, TValue value, CancellationToken ct = default)
{
    if (value == null)
    {
        return client.PostAsync(path, null, ct);
    }
        
    return client.PostAsJsonAsync(path, value, ct);
}

With the above code, the JsonProperty(Name) attribute is ignored. If I change the code as follows:

public static Task<HttpResponseMessage> PostExAsync<TValue>(this HttpClient client, string path, TValue value, CancellationToken ct = default)
{
    var json =  value != null ? JsonConvert.SerializeObject(value) : null;
    var content = value != null ? new StringContent(json, Encoding.UTF8, "application/json") : null;

    return client.PostAsync(path, content, ct);
}

It works. But why is the first method not working? I would rather use the first method instead of the second.

like image 324
Ivan Debono Avatar asked Oct 28 '25 03:10

Ivan Debono


1 Answers

The reason for this is that PostAsJsonAsync uses the System.Text.Json library, which has its own attribute: JsonPropertyNameAttribute.

In your second example, you're using JSON.NET, so given that it's working as you expect, it seems that your model is decorated with JsonPropertyAttribute.

If you want to use System.Text.Json everywhere that the model is used, then you should be able to just change your attributes to the ones from System.Text.Json. Otherwise, you could potentially decorate your property/properties with attributes for both libraries.

like image 152
DiplomacyNotWar Avatar answered Oct 29 '25 19:10

DiplomacyNotWar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!