[ApiController] 属性有什么作用?

What does the [ApiController] attribute do?

我注意到是否使用此属性是一回事。我错了吗?

举个例子:

[Route("[controller]")]
[ApiController]
public class DataTablesController: ControllerBase
{
    [HttpGet]
    public IActionResult Test()
    {
        return Ok("test");
    }
}

删除 [ApiController] 属性后没有任何反应。

在微软的文档中,我找到了这样的解释:

Indicates that a type and all derived types are used to serve HTTP API responses.
Controllers decorated with this attribute are configured with features and behavior targeted at improving the developer experience for building APIs.
When decorated on an assembly, all controllers in the assembly will be treated as controllers with API behavior.

API 行为是什么?我们为什么要使用它?

[ApiController] 属性启用了一些功能,包括属性路由要求、自动模型验证和绑定源参数推断。

这直接取自 MS 文档 Create web APIs with ASP.NET Core:

The [ApiController] attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors:

  • Attribute routing requirement
  • Automatic HTTP 400 responses
  • Binding source parameter inference
  • Multipart/form-data request inference
  • Problem details for error status codes

The Problem details for error status codes feature requires a compatibility version of 2.2 or later. The other features require a compatibility version of 2.1 or later.

以下功能的一些详细信息:

属性路由

如果使用[ApiController],则需要属性路由,例如:

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

Actions are inaccessible via conventional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in Startup.Configure

自动 Http 400 响应

如果 ModelState 验证失败,则将操作过滤器添加到 return 400 响应。你不再需要在你的动作中写这个,它会自动处理:

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

绑定源参数推断

同样,来自链接文档:

A binding source attribute defines the location at which an action parameter's value is found. The following binding source attributes exist: [FromBody], [FromForm], [FromHeader], [FromQuery], [FromRoute], [FromServices]

Multipart/form-data 请求推理

The [ApiController] attribute applies an inference rule when an action parameter is annotated with the [FromForm] attribute. The multipart/form-data request content type is inferred.

使用绑定源参数推断的示例:

[HttpPost]
public IActionResult Test([FromForm] Model model)
{
    return Ok("test");
}