.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 ...
随机推荐
- Java多线程分批发送消息的小例子
需求: 假设有10万个用户,现在节假日做活动,需要给每个用户发送一条活动短信,为了提高程序的效率,建议使用多线程分批发送. 这里值得注意的是: 每开一个线程都会占用CPU的资源,所以线程根据所需要的条 ...
- JSON数据格式:以及XML文件格式,YML文件格式,properties文件格式
JSON数据格式:以及XML文件格式,YML文件格式,properties文件格式 数据格式: json数据格式:属于轻量级数据格式,是javascript的一种描述数据的格式.具有易于解析,语法 ...
- ubuntu开发常用收集
命令: 1.http://blog.csdn.net/simongeek/article/details/45271089 2.http://www.jianshu.com/p/654be9c0f13 ...
- asp.net 报错 SAP 报错 试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)
“/”应用程序中的服务器错误. 试图加载格式不正确的程序. (异常来自 HRESULT:0x8007000B) 说明: 执行当前 Web 请求期间,出现未经处理的异常.请检查堆栈跟踪信息,以了解有关该 ...
- scp 基本用法(提高scp传输速度)
Outline spc 可以帮你实现: Linux Server 之间互传数据: Linux Server 和 Windows Server 之间互传数据: 参考: https://www.cnblo ...
- 第一次Git上传本地项目到github上 的命令
1.下载Git软件:https://git-scm.com/downloads, 2.下载之后安装就很简单了, 3.邮箱注册 在git bash界面输入如下内容即可完成邮箱的注册: $ git con ...
- 前端1-----CSS层叠样式表了解,css的引入方式,三大选择器(标签,类,id),高级选择器
前端1-----CSS层叠样式表了解,css的引入方式,三大选择器(标签,类,id),高级选择器 一丶CSS简介 叠样式表(英文全称:Cascading Style Sheets)是一种用来表现 ...
- vue前端实战注意事项
1. vue前端实战注意事项 1.1. 预备 1.1.1. Eslint 这是个语法检查工具,我用webstorm作为开发的ide,这个语法检查还是太严格了,一个空格啥的都会报错,对新手来讲还是建议关 ...
- 使用Beef劫持客户端浏览器并进一步使用Beef+msf拿客户端shell
环境: 1.Kali(使用beef生成恶意代码,IP:192.168.114.140) 2.一台web服务器(留言板存在XSS跨站脚本漏洞,IP:192.168.114.204) 3. 客户端(用于访 ...
- Win10下免安装版JDK8环境变量配置
1.解压JDK 2.配置JAVA_HOME环境变量 D:\Free\jdk1.8.0_92 3.配置CLASSPATH环境变量 .;%JAVA_HOME%\lib;%JAVA_HOME%\lib\to ...