Web框架 --- C#中的ActionFilter

Web框架 --- C#中的ActionFilter

  • 什么是Action Filter
  • 如何定义Action Filter
  • 如何使用ActionFilter

什么是Action Filter

  • Action Filter 是一种用于在执行controller方法之前或之后执行自定义逻辑的机制。>* Action Filter 可以用来处理各种任务,包括但 不限于
  • 日志记录、身份验证、授权、参数验证,错误处理和其他横切关注点(cross-cutting concerns)
  • C# Net Core 有四种常用的Filter (按照执行顺序排列)
  • Authorization filters – Implements the IAuthorizationFilter attribute.
  • Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.
  • Action filters – Implements the IActionFilter attribute. (最常用)
  • Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns.
  • Result filters – Implements the IResultFilter attribute.
  • Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
  • Exception filters – Implements the IExceptionFilter attribute.
  • Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
  • ActionFilter有两种方法可以执行
  • OnActionExecuting 在请求到达controller之前
  • OnActionExecuted 在请求被controller处理完之后

如何定义Action Filter

  • 定义一个Action Filter需要创建一个继承于 ActionFilterAttribute 的类
  • ActionFilterAttribute 同时实现了IActionFilter and IResultFilter interfaces and 并且继承了 Filter class.
  • 也就是继承了ActionFilterAttribute的类可以overide四个方法:
    OnActionExecuting – This method is called before a controller action is executed.
    OnActionExecuted – This method is called after a controller action is executed.
    OnResultExecuting – This method is called before a controller action result is executed.
    OnResultExecuted – This method is called after a controller action result is executed.

如何使用ActionFilter

全局使用

  • 可以对整个Application加入全局filter,在 Startup class里的ConfigureServices method定义
public void ConfigureServices(IServiceCollection services)
{services.AddMvc(options =>{options.Filters.Add(typeof(LogActionFilter));});
}

在所有Controller上使用

[LogActionFilter]
public class HomeController : Controller
{
// Controller action methods here
}

在单个Controller上使用

[LogActionFilter]
public IActionResult Index()
{
// Controller action method logic here
}

Example

using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;public class LogActionFilter : ActionFilterAttribute
{private Stopwatch stopwatch;public override void OnActionExecuting(ActionExecutingContext context){stopwatch = Stopwatch.StartNew();}public override void OnActionExecuted(ActionExecutedContext context){stopwatch.Stop();var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;var message = $"Action took {elapsedMilliseconds} ms to execute.";Debug.WriteLine(message);}
}

Filter还可以传参:

public class ResponseHeaderAttribute : ActionFilterAttribute
{private readonly string _name;private readonly string _value;public ResponseHeaderAttribute(string name, string value) =>(_name, _value) = (name, value);public override void OnResultExecuting(ResultExecutingContext context){context.HttpContext.Response.Headers.Add(_name, _value);base.OnResultExecuting(context);}
}
[ResponseHeader("Filter-Header", "Filter Value")]
public class ResponseHeaderController : ControllerBase
{public IActionResult Index() =>Content("Examine the response headers using the F12 developer tools.");// ...

Filter还可以改变request的参数

public class ValidateActionParametersAttribute : ActionFilterAttribute, IActionFilter{public override void OnActionExecuting(HttpActionContext actionExecutedContext){          var stringArgs = context.ActionArguments.Where(pair => pair.Value is string).ToList();foreach (var keyValue in stringArgs){var safeValue = ((string)keyValue.Value).Replace("\'", "");context.ActionArguments[keyValue.Key] = safeValue;}}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/883739.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于神经网络的农业病虫害损失预测

基于神经网络的农业病虫害损失预测 【摘 要】鉴于农业病虫害经济损失的预测具有较强的复杂性和非线性特性,设计了一种新型的GRNN预测模型,对农业病虫害经济损失进行预测。该模型基于人工神经网络捕捉非线性变化独特的优越性,在神经网络技术和…

DevCon,我们来了|DAOBase 线下活动(曼谷站)

随着数字化转型的加速,链上经济走在了前沿,为个人和社区赋能。链上金融可以无缝释放更多资金流,用户的链上身份拥有数据控制权,链上游戏能创造身临其境的新体验,许多团队正在打造 Web3 的未来。 本次活动将聚焦在开创…

python数据处理常用操作

数据处理是机器学习中非常重要的一步,以下是一些常用的操作和示例代码: 1. 数据清洗 处理缺失值: import pandas as pd# 读取数据 df pd.read_csv(data.csv)# 删除缺失值 df.dropna(inplaceTrue)# 用均值填充缺失值 df.fillna(df.mean(), i…

YOLO-FaceV2:A Scale and Occlusion Aware Face Detector

摘要 近年来,基于深度学习的人脸检测算法取得了巨大进展。这些算法一般可以分为两类,即像Faster R-CNN这样的两阶段检测器和像YOLO这样的一阶段检测器。由于一阶段检测器在精度和速度之间取得了更好的平衡,因此已被广泛应用于多种场景。在本…

贪心算法与盛雨水问题

啥是盛雨水问题?给个图就熟悉了 欸? 这其中的关键在于: 1. 容量2D化就是长 * 宽 2. 木桶效应:宽取决于短板。 那我们来分析,怎么样能达到最佳的结果呢?穷举一下所有可能性不就好了?每两个板子…

OAK相机的RGB-D彩色相机去畸变做对齐

▌低畸变标准镜头的OAK相机RGB-D对齐的方法 OAK相机内置的RGB-D管道会自动将深度图和RGB图对齐。其思想是将深度图像中的每个像素与彩色图像中对应的相应像素对齐。产生的RGB-D图像可以用于OAK内置的图像识别模型将识别到的2D物体自动映射到三维空间中去,或者产生的…

Information Theoretical Estimators (ITE) Toolbox的使用(MATLAB)

Information Theoretical Estimators (ITE) Toolbox是什么 官方文档: ITE is can estimate several entropy, mutual information, divergence, association measures, cross quantities and kernels on distributions. Thanks to its highly modular design, ITE …

STM32G474硬件CRC16和软件CRC16校验

1、硬件CRC校验和软件CRC校验的多项式,以及初始值 #define CRC_Hardware_POLYNOMIAL_16B 0x8005 //硬件CRC多项式为0x8005 //CRC16x^16 x^15 x^2 1,因为bit151,bit21,bit01,所以正向校验的多项式的值为0x8005 //CRC校验分为正向校验和反…

UWA Gears:Frame Capture模式 - 着色器查看器

UWA Gears 是UWA最新发布的无SDK性能分析工具。针对移动平台,提供了实时监测和截帧分析功能,帮助您精准定位性能热点,提升应用的整体表现。 在上周的文章中,我们详细介绍了网格查看器的功能,介绍如何通过网格数据优化…

微服务电商平台课程三:基础环境搭建

后端基础环境 工具版本号功能说明下载JDK1.8java编译运行的基本环境Java Downloads | Oracledocker27.0.3容器化部署Windows | Docker Docsgit2.46.2代码版本管理,多人协作代码开发Git for Windowsmaven3.9.9服务的依赖管理Maven – Download Apache MavenMySQL5.7…

【日常记录-Java】应用引入Slf4J

1. 简介 SLF4J(Simple Logging Facade for Java) 是Java的一个简单日志门面,为Java日志访问提供了一套标准、规范的API框架。而具体日志的实现则可以根据这套接口去实现具体的日志框架,以便将来需要更换日志框架时,只替换实现框架即可。常见的…

第十四章 章节练习echarts饼图渲染

目录 一、引言 二、完整代码 三、总结 一、引言 通过前面几个章节的学习,再结合日常项目中经常会使用到的echarts图,来完整以下功能需求,增强对知识点的巩固: 1. 基本渲染 2. 添加功能 3. 删除功能 4. 饼图渲染 运行效果图…

深入探讨全流量回溯分析与网络性能监控系统

AnaTraf 网络性能监控系统NPM | 全流量回溯分析 | 网络故障排除工具 随着数据量的急剧增加,传统的网络监控手段面临诸多挑战。在此背景下,全流量回溯分析和网络性能监控系统成为了保障网络正常运作的重要工具。本文将围绕这两个关键词,探讨它…

Python 深度学习简单介绍

文章目录 常用的深度学习框架1. TensorFlow2. PyTorch3. Keras4. MXNet 安装深度学习框架深度学习基础示例深度学习资源注意事项 Python 是一种高级编程语言,因其简洁的语法、丰富的库和社区支持,成为深度学习领域的主流编程语言。深度学习是一种机器学习…

厨艺爱好者的在线互动平台:Spring Boot实现

摘 要 使用旧方法对厨艺交流信息进行系统化管理已经不再让人们信赖了,把现在的网络信息技术运用在厨艺交流信息的管理上面可以解决许多信息管理上面的难题,比如处理数据时间很长,数据存在错误不能及时纠正等问题。 这次开发的厨艺交流平台功能…

WUP-MY-POS-PRINTER 旻佑热敏打印机票据打印uniapp插件使用说明

插件地址:WUP-MY-POS-PRINTER 旻佑热敏打印机票据打印安卓库 简介 本插件主要用于旻佑热敏打印机打印票据,不支持标签打印。适用于旻佑的各型支持票据打印的热敏打印机。本插件开发时使用的打印机型号为MY-805嵌入式面板打印机,其他型号请先…

2006-2023年各地级市债务余额数据

2006-2023年各地级市债务余额数据 1、时间:2006-2023年 2、来源:整理自wind 3、指标:地区、地方政府债-债券数量(只)、地方政府债-债券余额(亿)、地方政府债-债券余额占比(%)、城投债-债券数量(只)、城投债-债券余额(亿)、城投债-债券余额…

CentOS7安装Docker-2024

CentOS7安装Docker-2024 安装 更新yum仓库: yum -y update安装yum-utils并配置阿里云的docker仓库和相关插件: sudo yum install -y yum-utilsyum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repoyum i…

121.WEB渗透测试-信息收集-ARL(12)

免责声明:内容仅供学习参考,请合法利用知识,禁止进行违法犯罪活动! 内容参考于: 易锦网校会员专享课 上一个内容:120.WEB渗透测试-信息收集-ARL(11) 点击管理控制台 连接成功&…

Java | Leetcode Java题解之第513题找树左下角的值

题目&#xff1a; 题解&#xff1a; class Solution {public int findBottomLeftValue(TreeNode root) {int ret 0;Queue<TreeNode> queue new ArrayDeque<TreeNode>();queue.offer(root);while (!queue.isEmpty()) {TreeNode p queue.poll();if (p.right ! nu…