从ASP.NET MVC项目调用.NET Core 5 Web API微服务无法获取BadRequest错误详情
.NET Core MVC调用Web API无法获取ModelState校验错误的解决方案
调用端代码修正
你当前代码仅获取了响应状态码,没有主动读取响应体内容,这是最常见的原因,按如下方式修改调用代码即可:
var client = _httpClientFactory.CreateClient("test"); // 新增:声明接收JSON格式的响应,避免Web API返回非预期格式 client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(comment), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PutAsync($"api/comments", httpContent); // 新增:读取响应体内容 string responseContent = await response.Content.ReadAsStringAsync(); if ((int)response.StatusCode == 400) { // 反序列化为.NET内置的ValidationProblemDetails类型,直接匹配Swagger返回的结构 var validationError = System.Text.Json.JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ValidationProblemDetails>(responseContent, new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true }); // 遍历获取所有错误信息 foreach (var errorItem in validationError.Errors) { string field = errorItem.Key; string[] messages = errorItem.Value; // 此处即可拿到类似"The Remarks field is required."的提示 } }
Web API端配置校验
如果按上述代码仍读取不到内容,检查Web API项目Startup.cs中ConfigureServices方法的控制器配置,确认没有关闭默认模型校验响应:
- 移除以下错误配置(如果存在):
services.AddControllers() .ConfigureApiBehaviorOptions(options => { // 该配置会关闭默认的模型校验错误返回逻辑,必须删除 options.SuppressModelStateInvalidFilter = true; });
- 如果你自定义了模型校验响应工厂,确保返回
ValidationProblemDetails结构:
services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problem = new Microsoft.AspNetCore.Mvc.ValidationProblemDetails(context.ModelState) { Status = 400, Title = "One or more validation errors occurred." }; return new Microsoft.AspNetCore.Mvc.BadRequestObjectResult(problem); }; });
其他注意事项
- 不要在调用
PutAsync之后调用response.EnsureSuccessStatusCode(),该方法会在遇到400/500等错误状态码时直接抛出异常,无法读取响应内容 - 确认Web API端没有全局异常中间件拦截400响应并清空响应体
内容的提问来源于stack exchange,提问作者DO2021
相关产品推荐
相关产品推荐

