.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 ...
随机推荐
- RocketMQ Release Note(RocketMQ升级日志译文)
RocketMQ升级日志 1 4.2.0 原版Release Note 1.1 New Feature 支持传输层安全性 客户端支持log4j2 PushConsumer支持条数与大小维度的流控 1. ...
- 2019 游族网络java面试笔试题 (含面试题解析)
本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.游族网络等公司offer,岗位是Java后端开发,因为发展原因最终选择去了游族网络,入职一年时间了,也成为了面 ...
- linux环境:FTP服务器搭建
转载及参考至:https://www.linuxprobe.com/chapter-11.html https://www.cnblogs.com/lxwphp/p/8916664.html 感谢原作 ...
- kylin2.4.1订单案例详细构建流程
一.Hive订单数据仓库构建: hive表创建可以在命令行中直接完成,也可以在Hue中完成,本文在Hue中的完成,如下图: 下文的样例文本文件下载地址:https://files-cdn.cnblog ...
- 微信小程序中使用全局变量解决页面的传值问题
由于项目需要,最近便在做 一个类似于美团的餐饮平台的的微信微信小程序 ,项目有十几个页面,那么页面间的传值被经常用到.在小程序中页面间的传值主要有使用全局变量和本地存储这两种方法,在这个项目中我采用的 ...
- JavaSE01:初始Java
java语言的优势 简单性 面向对象 跨平台性(可移植性) 高性能 分布式 动态性 多线程 安全性 健壮性 java最大的特点是跨平台性 Java的跨平台性来源于Java虚拟机(jvm),Java靠在 ...
- javascript中的vavigator对象
appCodeName javaScript 1.0 介绍:与浏览器相关的内部代码名 appMinorVersion IE4及其后续的版本 介绍:辅版本号(通常应用于浏览器的补丁或服务包) appNa ...
- Vue学习之基础及部分指令小结(一)
一.理解MVC和MVVM的关系: MVC:Model View Controller (模型 视图 控制器) 分别为:业务逻辑.界面.用来调度View和Model层 MVVM:Model View V ...
- ES6 对象解构赋值(浅拷贝 VS 深拷贝)
对象的扩展运算符(...)用于取出参数对象的所有可遍历属性,拷贝到当前对象之中. 拷贝对象 let aa = { age: 18, name: 'aaa' } let bb = {...aa}; co ...
- 单元测试框架unitest和自动化测试高级应用
单元测试框架:为了让单元测试代码更容易维护和编写,遵循一定的规范来编写测试用例. 创建被测类calculator.py #计算器 class count: def _init_(self,a,b) ...