.NET Core跨API调用接口时请求对象接收为null的修复方法
接口调用时FromBody参数接收null的修复方案
问题场景
我在API 1中定义了如下POST接口:
[HttpPost] public ActionResult PostSchoolQuery([FromBody] SchoolQueryModel schoolQueryModel, [FromHeader] string authorization) { }
对应的请求模型类:
public class SchoolQueryModel { public List<Guid?> SchoolIds { get; set; } public List<Guid?> DistrictIds { get; set; } }
当我在API 2中通过以下代码调用上述接口时,API 1始终接收到schoolQueryModel为null,需要修复这个问题:
public ActionResult GetUserSchools(SchoolQueryModel getSchoolsModel) { dynamic schoolDetails = null; var requestContent = new JsonSerializer.Serialize(getSchoolsModel); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", _infrastructureAuthKey); var responseTask = client.PostAsync("http://localhost:6200/api/post_school_query", requestContent); if (responseTask.Result.IsSuccessStatusCode) { var readTask = responseTask.Result.Content.ReadAsAsync<JObject>(); readTask.Wait(); schoolDetails = readTask.Result; } } }
问题原因
- 请求内容格式不匹配:
JsonSerializer.Serialize返回的是字符串,但PostAsync需要传入HttpContent类型参数。直接传字符串会导致请求的Content-Type不是application/json,API 1无法正确解析Body内容。 - 异步操作使用错误:直接调用
.Result和.Wait()容易引发死锁,不符合异步编程规范。
修复后的代码
public async Task<ActionResult> GetUserSchools(SchoolQueryModel getSchoolsModel) { dynamic schoolDetails = null; // 将序列化后的字符串包装为StringContent,指定Content-Type为application/json var jsonContent = JsonSerializer.Serialize(getSchoolsModel); var requestContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", _infrastructureAuthKey); // 使用await替代同步阻塞调用,避免死锁 var response = await client.PostAsync("http://localhost:6200/api/post_school_query", requestContent); if (response.IsSuccessStatusCode) { schoolDetails = await response.Content.ReadAsAsync<JObject>(); } } return Ok(schoolDetails); }
额外注意事项
- 必须确保请求的
Content-Type头为application/json,这是[FromBody]能正确绑定模型的核心前提。 - 异步方法全程使用
async/await,避免混合同步阻塞调用,防止死锁和性能损耗。 - 提前校验API 2中的
getSchoolsModel是否有有效值,如果该参数本身为null,传递后API 1自然也会接收null。
内容的提问来源于stack exchange,提问作者Vasanth R
相关产品推荐
相关产品推荐

