ApiControllerAttribute 的 AspNet 核心 Web Api 使用 [英] AspNet core web Api usage of ApiControllerAttribute

查看:20
本文介绍了ApiControllerAttribute 的 AspNet 核心 Web Api 使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 API 项目中创建一个新的控制器时,它会生成一个带有 [ApiController] 属性的控制器类,如下所示:

When I create a new controller in the API project, it generates a controller class with [ApiController] attribute, like this:

[ApiController]
public class TestController : ControllerBase
{
 //implementation
}

我看过一些 webapi 项目,其中省略了此属性的使用.Microsoft 文档此处说:

I've seen a few webapi projects where usage of this attribute is omitted. Microsoft documentation here says:

表示一个类型和所有派生类型用于服务HTTP API回应.此属性的存在可用于定位基于目的的约定、过滤器和其他行为控制器.

Indicates that a type and all derived types are used to serve HTTP API responses. The presence of this attribute can be used to target conventions, filters and other behaviors based on the purpose of the controller.

但是,我还是不明白.有人可以用现实生活中的例子解释这个属性的目的是什么吗?

But still, I don't get the idea. Can someone explain what is the purpose of this attribute with the real-life example?

推荐答案

这在文档中有很好的解释:Annotation with ApiController 属性,说明添加[ApiController] 属性到控制器执行以下操作:

This is well-explained in the docs: Annotation with ApiController attribute, which explains that adding the [ApiController] attribute to a controller does the following:

  1. 自动 HTTP 400 响应

如果 ModelState.IsValidfalse,则添加返回 400 响应的操作过滤器.

Adds an action filter that returns a 400 response if ModelState.IsValid is false.

绑定源参数推断

更改模型绑定约定.例如,[FromBody] 是为复杂类型参数推断的.

Changes model-binding conventions. For example, [FromBody] is inferred for complex-type parameters.

多部分/表单数据请求推理

为标有 [FromForm] 的参数推断 multipart/form-data 的 Content-Type.

Infers a Content-Type of multipart/form-data for parameters marked with [FromForm].

属性路由要求

要求所有操作都必须进行属性路由.

Mandates that all actions must be attribute-routed.

您可以在 来源:

foreach (var actionModel in controllerModel.Actions)
{
    if (!isApiController && !actionModel.Attributes.OfType<IApiBehaviorMetadata>().Any())
    {
        continue;
    }

    EnsureActionIsAttributeRouted(controllerHasSelectorModel, actionModel);
    AddInvalidModelStateFilter(actionModel);
    InferParameterBindingSources(actionModel);
    InferParameterModelPrefixes(actionModel);
    AddMultipartFormDataConsumesAttribute(actionModel);
}

如果您对上述任何功能不感兴趣,可以省略该属性.还可以通过配置 ApiBehaviorOptions 类.

If you're not interested in any of the features described above, you can omit the attribute. It's also possible to suppress individual features by configuring the ApiBehaviorOptions class.

这篇关于ApiControllerAttribute 的 AspNet 核心 Web Api 使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆