【问题标题】:Can't retrieve BadRequest errors when calling .NET CORE 5 Web API microservice from ASP.NET MVC project从 ASP.NET MVC 项目调用 .NET CORE 5 Web API 微服务时无法检索 BadRequest 错误
【发布时间】:2021-11-29 21:44:53
【问题描述】:

我正在尝试从 ASP.NET Core MVC 前端使用 .NET Core 5 Web API 构建的微服务中检索 ModelState 验证错误。

假设我有一个看起来像这样的模型:

public class Comment
{
    public string Title { get; set; }
    [Required]
    public string Remarks { get; set; }
}

当我通过 Swagger 调用微服务中的 rest 端点以更新 Comment 模型而不加注释时,我得到如下响应正文:

{
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "Remarks": [
      "The Remarks field is required."
    ]
  }
}

太棒了!这是我所期望的......但是,当我通过我的 MVC 项目调用这个端点时,我似乎无法得到实际的“错误”。

这就是我调用其余端点的方式:

var client = _httpClientFactory.CreateClient("test");
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(comment), Encoding.UTF8, "application/json"); 
HttpResponseMessage response = await client.PutAsync($"api/comments", httpContent);

响应对象只有一个statusCodeBadRequest。我想提取有关错误的信息(显示“需要备注字段”的部分。)但我在 ContentHeaders 属性或类似的东西中看不到它。

我是微服务和 .NET Core 的新手——我做错了什么吗?我需要向startup.cs 添加一些内容吗?我可以得到BadRequest 状态但没有支持问题的详细信息,这似乎很奇怪。

提前致谢!

【问题讨论】:

    标签: asp.net-core-mvc asp.net-core-webapi asp.net-core-5.0 modelstate


    【解决方案1】:

    确保您的 Web api 控制器未使用 [ApiController] 声明。

    Web API 项目:

    //[ApiController]
    [Route("api/[controller]")]
    public class CommentsController : ControllerBase
    {
        [HttpPut]
        public IActionResult Put([FromBody] Comment model)
        {
            if(ModelState.IsValid)
            {
                //do your stuff...
                return Ok();
            }
            return BadRequest(ModelState);
        }
    }
    

    Mvc 项目:

    HttpResponseMessage response = await client.PutAsync($"api/comments", httpContent);
    var result = response.Content.ReadAsStringAsync().Result;
    

    【讨论】:

    • 谢谢!这使我找到了解决方案。我正在添加:response.EnsureSuccessStatusCode() 在响应返回后(忘记在原始帖子中提及),它正在消除错误详细信息。我在确定返回 BadResult() 或 Ok() 之前检查了 response.IsSuccessStatusCode,它现在可以工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多