.net core 从 ActionFilterAttribute 获取Request.Body 的正确方式
由于 ModelBinding在动作过滤器之前运行,直接使用 context.ActionArguments["parameter"] 获取模型对象
This article shows how to use an ActionFilter to validate the model from a HTTP POST request in an ASP.NET Core MVC application.
Code: https://github.com/damienbod/AngularAutoSaveCommands
2019-07-31: Updated to ASP.NET Core 3.0 Preview 7, Updated to Angular 8.1.3
2019-02-16: Updated to Angular 7.2.4, ASP.NET Core 2.2 nuget packages
2018-11-22: Updated to Angular 7.1.0, nuget packages
2018-09-28: Updated to ASP.NET Core 2.1.4 and Angular 6.1.9
2018-06-16: Updated to ASP.NET Core 2.1 and Angular 6.0.5
2018-02-11: Updated to ASP.NET Core All 2.0.5 and Angular 5.2.4
2017-08-19: Updated to ASP.NET Core 2.0 and Angular 4.3.5
2017.02.03: Updated to Angular 2.4.5 and webpack 2.2.1, VS2017 RC3, msbuild3
2016.12.23: Updated to Visual Studio 2017 and ASP.NET Core 1.1
Other articles in this series:
- Implementing UNDO, REDO in ASP.NET Core
- Angular Auto Save, Undo and Redo
- ASP.NET Core Action Arguments Validation using an ActionFilter
In an ASP.NET Core MVC application, custom validation logic can be implemented in an ActionFilter. Because the ActionFilter is processed after the model binding in the action execution, the model and action parameters can be used in an ActionFilter without having to read from the Request Body, or the URL.
The model can be accessed using the context.ActionArguments dictionary. The key for the property has to match the parameter name in the MVC Controller action method. Ryan Nowak also explained in this issue, that the context.ActionDescriptor.Parameters can also be used to access the request payload data.
If the model is invalid, the context status code is set to 400 (bad request) and the reason is added to the context result using a ContentResult object. The request is then no longer processed but short circuited using the terminology from the ASP.NET Core documentation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
using System; using System.IO; using System.Text; using AngularAutoSaveCommands.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; namespace AngularAutoSaveCommands.ActionFilters { public class ValidateCommandDtoFilter : ActionFilterAttribute { private readonly ILogger _logger; public ValidateCommandDtoFilter(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger( "ValidatePayloadTypeFilter" ); } public override void OnActionExecuting(ActionExecutingContext context) { var commandDto = context.ActionArguments[ "commandDto" ] as CommandDto; if (commandDto == null ) { context.HttpContext.Response.StatusCode = 400; context.Result = new ContentResult() { Content = "The body is not a CommandDto type" }; return ; } _logger.LogDebug( "validating CommandType" ); if (!CommandTypes.AllowedTypes.Contains(commandDto.CommandType)) { context.HttpContext.Response.StatusCode = 400; context.Result = new ContentResult() { Content = "CommandTypes not allowed" }; return ; } _logger.LogDebug( "validating PayloadType" ); if (!PayloadTypes.AllowedTypes.Contains(commandDto.PayloadType)) { context.HttpContext.Response.StatusCode = 400; context.Result = new ContentResult() { Content = "PayloadType not allowed" }; return ; } base .OnActionExecuting(context); } } } |
The ActionFilter is added to the services in the Startup class. This is not needed if the ActionFilter is used directly in the MVC Controller.
1
|
services.AddScoped<ValidateCommandDtoFilter>(); |
The filter can then be used in the MVC Controller using the ServiceFilter attribute. If the commandDto model is invalid, a BadRequest response is returned without processing the business in the action method.
1
2
3
4
5
6
7
8
|
[ServiceFilter( typeof (ValidateCommandDtoFilter))] [HttpPost] [Route( "Execute" )] public IActionResult Post([FromBody]CommandDto commandDto) { _commandHandler.Execute(commandDto); return Ok(commandDto); } |
Links
https://docs.asp.net/en/latest/mvc/controllers/filters.html
https://github.com/aspnet/Mvc/issues/5260#issuecomment-245936046
.net core 从 ActionFilterAttribute 获取Request.Body 的正确方式的更多相关文章
- 深入探究ASP.NET Core读取Request.Body的正确方式
前言 相信大家在使用ASP.NET Core进行开发的时候,肯定会涉及到读取Request.Body的场景,毕竟我们大部分的POST请求都是将数据存放到Http的Body当中.因为笔者日常开发所使用的 ...
- @Spring MVC 中几种获取request和response的方式
1.最简单方式:处理方法入参 例如: @RequestMapping("/test") @ResponseBody public void saveTest(HttpServlet ...
- Struts2获取request的几种方式汇总
Struts2获取request三种方法 struts2里面有三种方法可以获取request,最好使用ServletRequestAware接口通过IOC机制注入Request对象. 在Action中 ...
- .net core web api 获取request body的纯文本
本文代码 https://github.com/wuhaibo/readPlainTextDotNetCoreWepApi 总有些时候我们希望获得Request body 的纯文本 那么怎么做呢?很简 ...
- springMVC 中几种获取request和response的方式
1.最简单方式:参数 例如: @RequestMapping("/test") @ResponseBody public void saveTest(HttpServletRequ ...
- 在springMVC的controller中获取request,response对象的一个方法
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttr ...
- ASP.NET Core Web APi获取原始请求内容
前言 我们讲过ASP.NET Core Web APi路由绑定,本节我们来讲讲如何获取客户端请求过来的内容. ASP.NET Core Web APi捕获Request.Body内容 [HttpPos ...
- RequestContextHolder 很方便的获取 request
在 Spring boot web 中我们可以通过 RequestContextHolder 很方便的获取 request. ServletRequestAttributes requestAttri ...
- jeecg中的一个上下文工具类获取request,session
通过调用其中的方法可以获取到request和session,调用方式如下: HttpServletRequest request = ContextHolderUtils.getRequest();H ...
随机推荐
- SQL系列(十二)—— insert update delete
前言 这个系列的前面都一直在介绍查询select.但是SQL中十分广泛,按对数据的不同处理可以分为: DML:全称Data Manipulation Language,从名字上可以看出,DML是对数据 ...
- C# Modbus 数据读取 使用NModBus4库
ModBus通讯协议 方法名 作用 所需参数 返回值 对应功能码 ReadCoils 读取DO的状态 从站地址(8位) byte slaveAddress 起始地址(16位) ushort start ...
- json文件 乱码问题 根本解决办法
1 工具→自定义:2 点击 命令 标签:3 在上方单选区选中 菜单栏,下拉列表选 文件:4 点击 添加命令5 在类别中,找到文件,在右侧找到高级保存选项,确定6 然后可以通过下移调整该选项在文件菜单中 ...
- jQuery实现form表单基于ajax无刷新提交方法详解
本文实例讲述了jQuery实现form表单基于ajax无刷新提交方法.分享给大家供大家参考,具体如下: 首先,新建Login.html页面: <!DOCTYPE html PUBLIC &quo ...
- Debian忘记密码重置
前一阵子因为特殊原因我把一个网站的VPS服务器关闭了,结果竟把SSH密码忘了,也没有使用SSH密钥,因为上面还有网站文件不能选择重装,只能尝试在面板重置,但是面板返回结果一直是404我无法获得重置的密 ...
- ProviderManager
类ProviderManager java.lang.Object继承 org.jivesoftware.smack.provider.ProviderManager public final cla ...
- Map作为缓存使用
public class MapCache { /** * 默认存储1024个缓存 */ private static final int DEFAULT_CACHES = 1024; private ...
- Java自学-操作符 逻辑操作符
Java的逻辑运算符 逻辑运算符 示例 1 : 长路与 和 短路与 无论长路与还是短路与 两边的运算单元都是布尔值 都为真时,才为真 任意为假,就为假 区别: 长路与 两侧,都会被运算 短路与 只要第 ...
- Js中级复习
JS中级复习—— 1,this 就是js的关键字 用途:指向某一个对象 如何判断this指向: 函数(方法)内—— 一种以函数的方式调用(不带.)this指向window 一种以方法的形式调用(函 ...
- svn进行上传项目
当svn的服务器搭建成功后,就可以进行上传项目了. 右键,选择客户端的repo-browser, 输入地址 然后就可以浏览所有项目: 然后在版本仓库上,右键,add folder, 添加对应的文件夹即 ...