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

原文链接:传送门

ASP.NET Core 支持使用C#创建Restful风格的服务,也被称之为 Web APIs。一个Web API 使用 Controller 来处理请求。在Web API中Controller是继承自ControllerBase的类。这篇文章介绍了如何使用Controller来处理web API 的请求。

ControlleBase类

一个web API项目包括一个或者多个继承自ControllerBase的控制器。web API项目模板提供了一个作为开始的Controller:

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

不要通过继承 Controller 类来创建web API控制器。Controller继承自ControllerBase并且添加了对于试图的支持,因此其是用来处理web页面请求的,而不是web API请求。

但这个规则也有例外,如果你打算使用同一个控制器来服务于页面和web API,那么便继承Controller。

ControllerBase提供了许多属性和方法,其可用于处理HTTP 请求。举个例子,ControllerBase.CreatedAtAction返回一个201状态码。

[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<Pet> Create(Pet pet)
{
    pet.Id = _petsInMemoryStore.Any() ? 
             _petsInMemoryStore.Max(p => p.Id) + 1 : 1;
    _petsInMemoryStore.Add(pet);

    return CreatedAtAction(nameof(GetById), new { id = pet.Id }, pet);
}

如下是ControllerBase提供的方法的更多例子:

方法注意
BadRequest 返回400状态码
NotFound 返回404状态码
PhysicalFile 返回一个文件
TryUpdateModelAsync 激活模型绑定
TryValidateModel 激活模型验证

所有可用的方法和属性的列表,请查看 ControllerBase

特性

 Microsoft.AspNetCore.Mvc 命名空间提供了一些特性,其可用于配置web API控制器和动作方法的行为。如下例子使用特性来指定支持的HTTP动作谓词以及任何已知的可被返回的HTTP状态码。

[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<Pet> Create(Pet pet)
{
    pet.Id = _petsInMemoryStore.Any() ? 
             _petsInMemoryStore.Max(p => p.Id) + 1 : 1;
    _petsInMemoryStore.Add(pet);

    return CreatedAtAction(nameof(GetById), new { id = pet.Id }, pet);
}

如下是可用的特性的更多示例:

TABLE 2
AttributeNotes
[Route] 为控制器或者动作方法指定URL模式
[Bind] 指定为模型绑定所包含的前缀和属性
[HttpGet] 标识一个动作方法仅支持HTTP GET动作谓词
[Consumes] 指定一个动作方法所接收的数据类型
[Produces] 指定一个动作方法返回的数据类型

获取包含所有可用特性的列表,请参考Microsoft.AspNetCore.Mvc 命名空间。

ApiController 特性

[ApiController]特性可被用于一个控制器类以启用如下固定的,API特定的行为:

其中,Problem details for error status codes 特性需要的兼容性版本为2.2及以后,其他特性所需要的兼容性版本为2.1及以后。

在特定控制器上的特性

[ApiController]特性可被用于特定的控制器上,就如同如下来自于工程模板的示例:

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

应用于多个控制器的特性

在超过一个控制器上使用特性的一个方案是创建自定义的基类控制器类并使用[ApiController]特性类标记它。如下实例展示了一个自定义的基类以及一个继承于它的控制器类:

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

应用于程序集的特性

如果兼容性版本被设置为2.2及以后,[ApiController]可用于程序集上。在这种方式下,标记将web API的行为应用到程序集的所有控制器中。没有办法挑选单独的控制器。将程序集级别的特性应用于包围着Startup类的命名空间声明:

[assembly: ApiController]
namespace WebApiSample
{
    public class Startup
    {
        ...
    }
}
原文地址:https://www.cnblogs.com/qianxingmu/p/12926348.html