PostAsJsonAsync 忽略了 JsonProperty 名称属性。

huangapple go评论76阅读模式
英文:

PostAsJsonAsync ignoring JsonProperty name attribute

问题

The first method is not working because it uses client.PostAsync(path, null, ct) when value is null, and this does not include any JSON data in the request body. Therefore, the JsonProperty(Name) attribute is ignored because there is no JSON data to serialize.

The second method works because it explicitly serializes the value object to JSON using JsonConvert.SerializeObject(value) and then creates a StringContent object with the serialized JSON. This ensures that the JSON data is included in the request body, and the JsonProperty(Name) attribute is respected.

If you prefer to use the first method, you would need to modify it to include the JSON data explicitly when value is not null, similar to how the second method does it.

英文:

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.

答案1

得分: 3

这是因为 PostAsJsonAsync 使用了 System.Text.Json 库,该库具有自己的属性:JsonPropertyNameAttribute

在第二个示例中,您正在使用 JSON.NET,因此考虑到它按您的期望工作,似乎您的模型已用 JsonPropertyAttribute 装饰。

如果您想在使用模型的所有地方都使用 System.Text.Json,那么您应该能够只是更改属性为来自 System.Text.Json 的属性。否则,您可能可以为两个库装饰您的属性/属性。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月25日 22:36:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定