浅谈 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 ...
随机推荐
- 「AGC034D」 Manhattan Max Matching
「AGC034D」 Manhattan Max Matching 传送门 不知道这个结论啊... (其实就是菜嘛) 首先 \(O(n^2)\) 的建边显然不太行. 曼哈顿距离有这样一个性质,如果将绝对 ...
- clickhouse分布式集群
一.环境准备: 主机 系统 应用 ip ckh-01 centos 8 jdk,zookeeper,clickhouse 192.168.205.190 ckh-02 centos 8 jdk,zoo ...
- 【LeetCode】12. 整数转罗马数字
12. 整数转罗马数字 知识点:字符串 题目描述 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 100 ...
- 关于 junit4 90% 的人都不知道的特性,详解 junitperf 的实现原理
前言 上一节介绍了 https://github.com/houbb/junitperf 的入门使用. 这一节我们从源码的角度,剖析一下其实现方式. 性能测试该怎么做? Junit Rules jun ...
- JavaScript实现拖放效果
JavaScript实现拖放效果 笔者实现该效果也是套用别人的轮子的.传送门 然后厚颜无耻的贴别人的readme~,笔者为了方便查阅就直接贴了,有不想移步的可以看这篇.不过还是最好请到原作者的GitH ...
- 第3天 IDEA 2021简单设置与优化 Java运算符 包机制
IDEA 2021简单设置与优化 将工具条显示在上方 View–>Appearance–>Toolbar 鼠标悬停显示 File–>setting–>Editor–>Ge ...
- Python自动化测试面试题-MySQL篇
目录 Python自动化测试面试题-经验篇 Python自动化测试面试题-用例设计篇 Python自动化测试面试题-Linux篇 Python自动化测试面试题-MySQL篇 Python自动化测试面试 ...
- 利用C++11可变模板,封装调用dll导出函数
起因 开发中经常需要动态调用一些导出函数,试着利用C++11特性封装一下 尝试 常规使用 typedef int WINAPI (*TMessageBoxA)(HWND hWnd,LPCSTR lpT ...
- Python -- 让程序运行后不立即关闭窗口
程序运行完毕,窗口也跟着关闭.也就是说还没来得及看结果,程序窗口就关闭了. 试着改改代码,在最后加上以下这行代码: raw_input("Press <enter>") ...
- python -- 负数平方根-虚数的使用
负数的平方根是虚数. 不能使用sqrt,因为它只能处理浮点数,而虚数是完全不同的--这也是由另外一个叫做cmath(即 complex math, 复数)的模块来实现这些功能的原因. >> ...