C# Webapi中[ApiController]特性的功能,即使用

第一:背景:

之前对这个特性一知半解,了解的不够深入,在试用期的工作中,问到这个特性,需要深入了解

第二个:正文,作用及使用

//[ApiController]
    //启用下述 API 特定的固定行为:
    /*
     * •特性路由要求
      不能通过由 Startup.Configure 中的 UseEndpoints、UseMvc 或 UseMvcWithDefaultRoute 定义的传统路由访问操作。即写[Route()]
       •自动 HTTP 400 响应
      使模型验证错误自动触发 HTTP 400 响应
       •绑定源参数推理
      [ApiController] 特性将推理规则应用于操作参数的默认数据源。 
      借助这些规则,无需通过将属性应用于操作参数来手动识别绑定源。 绑定源推理规则的行为如下:
      [FromBody],[FromForm],[FromRoute],[FromQuery],
      额外推理规则[FromServies],[FromHeader]
       •Multipart/form-data 请求推理
      使用 [FromForm] 属性批注操作参数时,将推断 multipart/form-data 请求内容类型。
      •错误状态代码的问题详细信息
      当兼容性版本为 2.2 或更高版本时,MVC 会将错误结果(状态代码为 400 或更高的结果)转换为状态代码为 ProblemDetails 的结果。
      ProblemDetails 类型基于 RFC 7807 规范,用于提供 HTTP 响应中计算机可读的错误详细信息。

关于它的使用,

使用范围:

一个控制器,多个控制器,应用程序级别的

特定控制器上的属性Attribute on specific controllers

[ApiController] 属性可应用于特定控制器,如项目模板中的以下示例所示:The [ApiController] attribute can be applied to specific controllers, as in the following example from the project template:

C#复制

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

C#复制

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase

多个控制器上的属性Attribute on multiple controllers

在多个控制器上使用该属性的一种方法是创建通过 [ApiController] 属性批注的自定义基控制器类。One approach to using the attribute on more than one controller is to create a custom base controller class annotated with the [ApiController] attribute. 下述示例展示了自定义基类以及从其派生的控制器:The following example shows a custom base class and a controller that derives from it:

C#复制

[ApiController]
public class MyControllerBase : ControllerBase
{
}

C#复制

[Produces(MediaTypeNames.Application.Json)]
[Route("[controller]")]
public class PetsController : MyControllerBase

C#复制

[Produces(MediaTypeNames.Application.Json)]
[Route("api/[controller]")]
public class PetsController : MyControllerBase

程序集上的属性Attribute on an assembly

如果将兼容性版本设置为 2.2 或更高版本,则 [ApiController] 属性可应用于程序集。If compatibility version is set to 2.2 or later, the [ApiController] attribute can be applied to an assembly. 以这种方式进行注释,会将 web API 行为应用到程序集中的所有控制器。Annotation in this manner applies web API behavior to all controllers in the assembly. 无法针对单个控制器执行选择退出操作。There's no way to opt out for individual controllers. 将程序集级别的属性应用于 Startup 类两侧的命名空间声明:Apply the assembly-level attribute to the namespace declaration surrounding the Startup class:

C#复制

[assembly: ApiController]
namespace WebApiSample
{
    public class Startup
    {
        ...
    }
}

如:

详细见官方文档,https://docs.microsoft.com/zh-cn/aspnet/core/web-api/?view=aspnetcore-3.1#apicontroller-attribute

重要的事情说三遍:看官方文档,看官方文档,看官方文档

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值