从 ASP.NET MVC 项目调用 .NET CORE 5 Web API 微服务时无法检索 BadRequest 错误

问题描述 投票:0回答:2

我正在尝试从 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);

响应对象的

statusCode
BadRequest
。我想提取有关错误的信息(“备注字段为必填项”部分),但我在
Content
Headers
属性或类似内容中没有看到它。

我是微服务和 .NET Core 的新手 - 我做错了什么吗?我需要在

startup.cs
中添加一些东西吗?看起来很奇怪,我可以获得
BadRequest
状态,但没有支持问题详细信息。

提前致谢!

asp.net-core-mvc asp.net-core-webapi asp.net-core-5.0 modelstate
2个回答
0
投票

确保您的 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;

0
投票

如果您想像在 .NetFramework 中所做的那样验证“ModelState”,您可以采用以下方法,

  1. 方法1

您可以在端点请求中验证 ModelState,同时在 program.cs/startup.cs 中添加以下代码片段

builder.Services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });

这次您不会收到 BadRequest (400) ,而是可以调用端点并验证您的“ModelState”。

  1. 方法2

相反,当模型状态无效时,您可以获取 BadRequest 响应,并在 Web/客户端控制器中显式处理响应。

  1. 方法3

如果你想处理自定义验证错误响应,那么你可以像 FluentValidation 或其他那样

参考:https://medium.com/codex/custom-error-responses-with-asp-net-core-6-web-api-and-fluidation-888a3b16c80f

礼貌:Medium.com

© www.soinside.com 2019 - 2024. All rights reserved.