【译】ASP.NET Core Web APIs(一):使用ASP.NET Core创建Web APIs 【下篇】

特性路由需求

[ApiConroller]特性使得特性路由成为一个需求。举个例子:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase

通过由 Startup.Configure中的UseEndpointsUseMvc,或者r UseMvcWithDefaultRoute方法定义的常规路由是不能访问Action方法的。

自动HTTP 400 响应

[ApiController] 特性使得模型验证错误自动触发一个HTTP 400 响应。因此,在一个Action方法中,如下代码是不必要的:

if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}

ASP.NET Core MVC使用ModelStateInvalidFilter 这个动作过滤器来进行上述检查。

默认的BadRequest响应

使用兼容性版本2.1,对于一个HTTP 400响应的默认响应类型是SerializableError。如下的请求体是一个序列化类型的示例:

{
  "": [
    "A non-empty request body is required."
  ]
}

使用兼容性版本2.2及以后,那么对于一个HTTP 400响应,默认的响应类型是 ValidationProblemDetails。如下的请求体是一个序列化类型的示例:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|7fb5e16a-4c8f23bbfc974667.",
  "errors": {
    "": [
      "A non-empty request body is required."
    ]
  }
}

这个ValidationProblemDetails 类型:

  • 对于在web API中指定错误,提供了一个机器可读的格式。
  • 使用 RFC 7807 specification 进行编译。

记录自动的HTTP 400 响应

请参考How to log automatic 400 responses on model validation errors (aspnet/AspNetCore.Docs #12157)

猜你喜欢

转载自www.cnblogs.com/qianxingmu/p/12960764.html