浅谈 asp.net core web api
希望通过本文能够了解如下内容:
ControllerBase
当我们开始实际上项目, 真正实操 anc 时, 肯定会用到 web api 框架和 mvc 框架. 这两个框架自动创建的 controller 继承了不同的父类, web api 创建的 controller 自动继承 controllerBase, mvc 创建的 controller 自动继承 controller, 两个区别是是否支持 views.
官网说了, 如果你的项目准备使用 web api的话, 不要创建一个继承自 controller 的 controller, 因为 controller 是带有一些 view 支持的. 并且 controller 本身也是继承自 controllerbase, 既然你是 web api 的controller, 去 handle web api request, 那么自然是不需要支持 views的, 所以直接使用 controllerbase. 但是有一种情况是例外的, 当你的controller同时想支持 web api 和 views 的时候, 那就继承 controller.
在抽象类 ControllerBase 中, 可以看到绝大多数定义的方法都是 xxxResult 方法. 我们细数一下ControllerBase为我们提供的Result都有哪些:
| Result name | des |
|---|---|
| Accepted Result | 创建一个status code 为202 accepted 的result作为response返回. |
| AcceptedAtAction Result | 创建一个status code 为202 accepted 的result作为response返回. |
| AcceptedAtRoute Result | 创建一个status code 为202 accepted 的result作为response返回. |
| BadRequestObject Result | Status400BadRequest |
| Challenge Result | 返回身份认证失败的401 unauthorized 和 权限校验失败的 403 forbidden result |
| ConflictObject Result | Status409Conflict |
| Conflict Result | Status409Conflict |
| Content Result | 返回指定的content string作为result |
| Created Result | Status201Created |
| CreatedAtAction Result | Status201Created |
| CreatedAtRoute Result | Status201Created |
| VirtualFile Result | Returns the file specified by virtualPath (Microsoft.AspNetCore.Http.StatusCodes.Status200OK) |
| FileStream Result | Returns a file in the specified fileStream (Microsoft.AspNetCore.Http.StatusCodes.Status200OK) |
| FileContent Result | Returns a file with the specified fileContents as content (Microsoft.AspNetCore.Http.StatusCodes.Status200OK) |
| ForbidResult | 权限校验失败的 403 forbidden result |
| LocalRedirect Result | Creates a Microsoft.AspNetCore.Mvc.LocalRedirectResult object that redirects (Microsoft.AspNetCore.Http.StatusCodes.Status302Found) to the specified local localUrl. |
| NoContent Result | Status204NoContent |
| NotFoundObject Result | Status404NotFound |
| Ok Result | Status200OK |
| PhysicalFile Result | Returns the file specified by physicalPath (Microsoft.AspNetCore.Http.StatusCodes.Status200OK) |
| Object Result | 比较灵活, 需要后端api 开发人员手动指定 status code和问题展示细节等. |
| Redirect Result | Creates a Microsoft.AspNetCore.Mvc.RedirectResult object that redirects (Microsoft.AspNetCore.Http.StatusCodes.Status302Found) to the specified url. |
| RedirectToAction Result | Redirects (Microsoft.AspNetCore.Http.StatusCodes.Status302Found) to an action with the same name as current one. The 'controller' and 'action' names are retrieved from the ambient values of the current request. |
| RedirectToPage Result | Redirects (Microsoft.AspNetCore.Http.StatusCodes.Status302Found) to the specified pageName. |
| RedirectToRouteResult | Redirects (Microsoft.AspNetCore.Http.StatusCodes.Status302Found) to the specified route using the specified routeName, routeValues, and fragment. |
| SignIn Result | 使用指定的身份认证信息创建的登录result |
| SignOut Result | 使用指定的身份认证信息登出系统的result |
| Object Result | 返回指定的code和value作为result |
| StatusCode Result | 返回指定的code作为result |
| UnauthorizedObject Result | Status401Unauthorized |
| Unauthorized Result | Status401Unauthorized |
| UnprocessableEntityObject Result | Status422UnprocessableEntity |
基本上很全了. 当我们实际使用时具体需要返回啥样的result, 可以随时去找一个对应合适的result放到response中返回去.
Attributes
除此外, 框架提供了很多 Attribute 用于定义 web api 中 controller 和 action 的行为.
[ApiController]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
自动生成的 controller 文件头上面还有个标签叫做 [ApiControllerAttribute], 它是用于启动一些专门为了 api 设定的配置.
ApiController 可以定义的位置
如果你的项目中有很多自定义的controller, 但是又不想一个一个都给打上标签, 可以声明一个父类controller, 在这个父类的controller上面打上[ApiController]标签, 并且在父类中定义一些common的method, 自定义的controller可以继承自该父类controller.
除了在controller的上面定义, 还可以在 startup 中定义. 这样做有个问题就是所有的controller都相当于定义了该标签, 无法例外:
[assembly: ApiController]
namespace WebApiSample
{
public class Startup
{
...
}
}
相当于路由的方式必须是标签路由方式
当 controller 上头被定义了该标签后, 表示路由的方式必须是通过标签定义
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
此时通过URL那种转义方式的路由就无法work了. 即我们在 startup.cs文件的configure方法里面通过 seEndpoints, UseMvc, or UseMvcWithDefaultRoute 这些方法定义的默认URL的转义会失效.
自动触发 http 400 code 的response
当 model validation 失败后, 会自动触发 http 400 code 的response, 所以下面的代码在一个 API 的 action 中是多余的:
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
如何禁用这一默认行为? 可以在 startup.cs中按照如下进行配置:
services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressConsumesConstraintForFormFileParameters = true;
options.SuppressInferBindingSourcesForParameters = true;
options.SuppressModelStateInvalidFilter = true;
options.SuppressMapClientErrors = true;
options.ClientErrorMapping[404].Link =
"https://httpstatuses.com/404";
});
使用[FromBody]参数标签对参数的数据源进行绑定 - model binding
可以在 action 的参数中使用一些参数标签来确定参数的来源.这种操作被称为 model binding, 可以作为 model binding 的参数标签如下:
| Attribute | Binding source |
|---|---|
| [FromBody] | 从http Request body中获取参数值. 不要在一个action中使用多余一个FromBody标签, 不支持这种操作. |
| [FromForm] | 从httprequest body的form字段中获取参数值. |
| [FromHeader] | 从 http headers 中获取参数值. |
| [FromQuery] | 从query string中获取参数参数值. 但是支持持简单类型的数据获取 |
| [FromRoute] | 从当前request的RouteData中获取参数数据参数值. 只支持简单类型的参数(注意当你的values中有可能包含 %2f 时, 不要使用这个标签, 而是使用 [FromQuery], 因为在 [FromRoute] 中 %2f 不会按照理想的方式转义为 /. ) |
| [FromServices] | 这种情况是在你的action中使用了其他类的一个实例, 一般来说都是通过依赖注入的方式获取类的实例, 构造函数中注入的话, 可能没有必要. 因为只有这一个方法使用. 所以在参数中添加[FromServices]来获取. |
Action的返回值类型
浅谈 asp.net core web api的更多相关文章
- List多个字段标识过滤 IIS发布.net core mvc web站点 ASP.NET Core 实战:构建带有版本控制的 API 接口 ASP.NET Core 实战:使用 ASP.NET Core Web API 和 Vue.js 搭建前后端分离项目 Using AutoFac
List多个字段标识过滤 class Program{ public static void Main(string[] args) { List<T> list = new List& ...
- ASP.NET Core Web API 跨域(CORS) Cookie问题
身为一个Web API,处理来自跨域不同源的请求,是一件十分合理的事情. 先上已有的文章,快速复制粘贴,启用CORS: Microsoft:启用 ASP.NET Core 中的跨域请求 (CORS) ...
- 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)
对于开发人员来说,构建一个消费应用程序时去了解各种各样的 API 是一个巨大的挑战.在你的 Web API 项目中使用 Swagger 的 .NET Core 封装 Swashbuckle 可以帮助你 ...
- 在ASP.NET Core Web API上使用Swagger提供API文档
我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的API文档功能.当设置IISExpress的默认启动路由到Swagger的API文档页 ...
- Docker容器环境下ASP.NET Core Web API应用程序的调试
本文主要介绍通过Visual Studio 2015 Tools for Docker – Preview插件,在Docker容器环境下,对ASP.NET Core Web API应用程序进行调试.在 ...
- 在docker中运行ASP.NET Core Web API应用程序
本文是一篇指导快速演练的文章,将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤,在介绍的过程中,也会对docker的使用进行一些简单的描述.对于.NET Cor ...
- ASP.NET Core Web API Cassandra CRUD 操作
在本文中,我们将创建一个简单的 Web API 来实现对一个 “todo” 列表的 CRUD 操作,使用 Apache Cassandra 来存储数据,在这里不会创建 UI ,Web API 的测试将 ...
- 在Mac下创建ASP.NET Core Web API
在Mac下创建ASP.NET Core Web API 这系列文章是参考了.NET Core文档和源码,可能有人要问,直接看官方的英文文档不就可以了吗,为什么还要写这些文章呢? 原因如下: 官方文档涉 ...
- ASP.NET Core Web API 开发-RESTful API实现
ASP.NET Core Web API 开发-RESTful API实现 REST 介绍: 符合REST设计风格的Web API称为RESTful API. 具象状态传输(英文:Representa ...
随机推荐
- 交通规则:HOV车道
多乘员车道的限行时间一般为工作日上下班高峰,车上只有一个人时不能走该车道
- mysql:insert replace
在使用SQL语句进行数据表插入insert操作时,如果表中定义了主键,插入具有相同主键的记录会报错: Error Code: 1062. Duplicate entry 'XXXXX' for key ...
- docker容器技术基础之linux cgroup、namespace
一.开头 接触过docker的同学多多少少听过这样一句话"docker容器通过linux namespace.cgroup特性实现资源的隔离与限制".今天我们来尝试学习一下这两个东 ...
- SpringBoot配置Https
HTTPS (全称:Hyper Text Transfer Protocol over SecureSocket Layer),是以安全为目标的 HTTP 通道,在HTTP的基础上通过传输加密和身份认 ...
- [刘阳Java]_处理并发有哪些方法
1.HTML静态化 ,将活动页面上的所有可以静态的元素全部静态化,并尽量减少动态元素2.禁止重复提交:用户提交之后按钮置灰,禁止重复提交3.用户限流:在某一时间段内只允许用户提交一次请求,比如可以采取 ...
- ubuntu平台下,字符集的转换命令iconv
iconv命令格式 iconv -f 源字符集(要转换文件的字符集) -t 目标字符集 file iconv -f gb18030 -t utf-8 file 默认情况下,不改变原文件,输出到屏幕. ...
- Appium - adb monkey事件(二)
操作事件简介 Monkey所执行的随机事件流中包含11大事件,分别是触摸事件.手势事件.二指缩放事件.轨迹事件.屏幕旋转事件.基本导航事件.主要导航事件.系统按键事件.启动Activity事件.键盘事 ...
- C++:数据类型
/** * C++ 数据类型 : https://www.runoob.com/cplusplus/cpp-data-types.html * * 布尔: bool * 字符: char 1 个字节 ...
- PHP如何接收json数据
以前一直在写一些网站,很少涉及到接口的东西.最近公司在做一个平台,需要往接口上发送json数据.闲话少叙,直接上干货. 在php中可以通过如下方式获取: file_get_contents(" ...
- 基于pygame框架的打飞机小游戏
import pygame from pygame.locals import * import time import random class Base(object): "" ...