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

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

问题描述

当我在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?

推荐答案

这在文档中得到了很好的解释:

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]的参数推断Content-Type为multipart/form-data.

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

强制所有动作必须进行属性路由.

Mandates that all actions must be attribute-routed.

您可以在如果您对上述任何功能均不感兴趣,则可以忽略该属性.通过配置

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.

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

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