HttpPost请求PostAsJsonAsync序列化JsonPropertyName不生效配置问询
解决方案
问题根因
你使用的PostAsJsonAsync方法默认基于System.Text.Json实现序列化,出现属性名不匹配的问题通常是两个原因:
- 引用了错误的
JsonPropertyName特性(比如混用Newtonsoft.Json和System.Text.Json的特性) - 序列化器默认启用了自动命名策略,覆盖了特性指定的属性名
修复步骤
- 核对特性引用
确认Request类顶部的引用是:
using System.Text.Json.Serialization;
不要误用Newtonsoft.Json.JsonProperty特性,System.Text.Json序列化器无法识别第三方库的特性。
- 显式指定序列化配置
调用PostAsJsonAsync时传入自定义序列化选项,关闭自动命名策略,优先读取属性上的JsonPropertyName配置,修改后的代码如下:
public async Task<Result> PostAsync([FromBody]Request request, [FromHeader(Name = "Cs-Auth")] string authKey=null) { try{ // 定义序列化配置 var serializeOptions = new JsonSerializerOptions { // 关闭自动命名转换,完全按照JsonPropertyName的配置输出属性名 PropertyNamingPolicy = null, // 反序列化时也兼容属性名大小写差异,可选配置 PropertyNameCaseInsensitive = true }; // 传入配置参数 HttpResponseMessage response = await httpClient.PostAsJsonAsync(_config.ApiUrl, request, serializeOptions); response.EnsureSuccessStatusCode(); string responseText = await response.Content.ReadAsStringAsync(); // 反序列化也用相同配置避免不兼容 Result result = JsonSerializer.Deserialize<Result>(responseText, serializeOptions); return ProcessResult(result); } catch(Exception e) { _logger.LogError(e.ToString()); throw; } }
替代方案(使用Newtonsoft.Json序列化)
如果你的项目默认使用Newtonsoft.Json做序列化,可直接手动构造请求内容,避免System.Text.Json的兼容性问题:
// 用Newtonsoft序列化请求对象 var requestJson = JsonConvert.SerializeObject(request); var content = new StringContent(requestJson, System.Text.Encoding.UTF8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync(_config.ApiUrl, content);
内容的提问来源于stack exchange,提问作者Daolin
相关产品推荐
相关产品推荐

