基础教程:ASP.NET Core 2.0 MVC筛选器
问题
如何在ASP.NET Core的MVC请求管道之前和之后运行代码。
解
在一个空的项目中,更新 Startup 类以添加MVC的服务和中间件。
publicvoid ConfigureServices
(IServiceCollection services)
{
services.AddMvc();
}
publicvoid Configure(
IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
添加类来实现过滤器。
publicclass ParseParameterActionFilter : Attribute, IActionFilter
{
publicvoid OnActionExecuting(ActionExecutingContext context)
{
object param;
if (context.ActionArguments.TryGetValue("param", out param))
context.ActionArguments["param"] = param.ToString().ToUpper();
else
context.ActionArguments.Add("param", "I come from action filter");
}
publicvoid OnActionExecuted(ActionExecutedContext context)
{
}
}
在Home控制器中添加一个使用Action过滤器的操作方法,
[ParseParameterActionFilter]
public IActionResult ParseParameter(string param)
{
return Content($"Hello ParseParameter. Parameter: {param}");
}
浏览到 / Home / ParseParameter; 你会看到的 -
讨论
筛选器在选择执行操作方法后运行。MVC为授权和缓存等内容提供了内置的过滤器。自定义过滤器对于封装要在动作方法之前或之后运行的可重用代码非常有用。
过滤器可能导致结果短路,即停止运行中的代码,并将结果返回给客户端。他们也可以通过服务容器注入 服务,这使得他们非常灵活。
过滤器接口
创建自定义过滤器需要实现您所需的过滤器类型的接口。大多数过滤器类型有两种类型的接口 - 同步和异步。
publicclass HelloActionFilter : IActionFilter
{
publicvoid OnActionExecuting(ActionExecutingContext context)
{
// runs before action method
}
publicvoid OnActionExecuted(ActionExecutedContext context)
{
// runs after action method
}
}
publicclass HelloAsyncActionFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
// runs before action method
await next();
// runs after action method
}
}
您可以通过在上下文参数(对于异步过滤器,不要调用下一个 委托)中设置Result (类型 IActionResult)属性 来短路过滤器管道 。
publicclass SkipActionFilter : Attribute, IActionFilter
{
publicvoid OnActionExecuting(ActionExecutingContext context)
{
context.Result = new ContentResult
{
Content = "I'll skip the action execution"
};
}
publicvoid OnActionExecuted(ActionExecutedContext context)
{ }
}
[SkipActionFilter]
public IActionResult SkipAction()
{
return Content("Hello SkipAction");
}
对于结果过滤器,可以通过 在上下文参数上设置取消属性并发送响应来进行短路 。
public void OnResultExecuting(ResultExecutingContext context)
{
context.Cancel = true ;
context.HttpContext.Response.WriteAsync(“我将跳过结果执行” );
}
[SkipResultFilter]
public IActionResult SkipResult()
{
返回 内容(“Hello SkipResult” );
}
过滤器属性
MVC提供了可以继承的抽象基类来创建自定义过滤器。这些抽象类继承自 Attribute 类,因此可以用来装饰控制器和操作方法。
ActionFilterAttribute
ResultFilterAttribute
ExceptionFilterAttribute
ServiceFilterAttribute
TypeFilterAttribute
过滤器类型
在过滤器管道的不同阶段有各种类型的过滤器。下面,官方文件中的一个数字说明了顺序:
授权
这是运行的第一个过滤器,并将对未经授权的用户的请求短路。他们只有一个方法(不同于其他大多数具有执行 和 执行 方法的过滤器 )。通常情况下,您不会编写自己的授权过滤器,内置过滤器调用到框架的授权机制中。
资源
它们在模型绑定之前运行,可以用来改变它的行为。而且,它们在结果生成后运行,可用于缓存等。
行动
它们在动作方法之前和之后运行,因此对操作动作参数或其结果非常有用。提供给这些过滤器的上下文让您可以操作动作参数,控制器和结果。
例外
它们可以在写入响应之前用于未处理的异常。异常处理中间件适用于大多数场景,但是如果您想根据调用的操作以不同方式处理错误,则可以使用此过滤器。
结果
如果结果成功,它们在执行操作方法的结果之前和之后运行。他们可以用来操纵结果的格式。
过滤范围
可以在不同级别的范围添加过滤器:Action,Controller和Global。属性用于动作和控制器级作用域。对于全局范围的过滤器,您需要添加它们以 在启动时配置服务时 过滤MvcOptions的集合 ,
services.AddMvc(options =>
{
// by instance
options.Filters.Add(new AddDeveloperResultFilter("Tahir Naushad"));
// by type
options.Filters.Add(typeof(GreetDeveloperResultFilter));
});
过滤器按顺序执行
的 执行 方法是首先呼吁全球>控制器>动作过滤器。
然后 为Action> Controller> Global过滤器调用已执行的方法。
过滤依赖注入
为了使用需要在运行时注入依赖关系的过滤器,您需要通过Type添加它们。您可以将它们全局添加(如上所述),但是,如果要将它们应用于操作或控制器(作为属性),则有两个选项:
ServiceFilterAttribute
此属性使用服务容器检索过滤器。要使用它,
创建一个使用依赖注入的过滤器 ,
publicclass GreetingServiceFilter : IActionFilter
{
private readonly IGreetingService greetingService;
public GreetingServiceFilter(IGreetingService greetingService)
{
this.greetingService = greetingService;
}
publicvoid OnActionExecuting(ActionExecutingContext context)
{
context.ActionArguments["param"] =
this.greetingService.Greet("James Bond");
}
publicvoid OnActionExecuted(ActionExecutedContext context)
{ }
}
将过滤器添加到服务容器
services.AddScoped<GreetingServiceFilter>();
使用ServiceFilterAttribute应用它
[ServiceFilter(typeof(GreetingServiceFilter))]
public IActionResult GreetService(string param)
TypeFilterAttribute
该属性不需要在服务容器中注册过滤器,并使用ObjectFactory 委托启动类型 。使用它
创建一个使用依赖注入的过滤器
publicclass GreetingTypeFilter : IActionFilter
{
private readonly IGreetingService greetingService;
public GreetingTypeFilter(IGreetingService greetingService)
{
this.greetingService = greetingService;
}
publicvoid OnActionExecuting(ActionExecutingContext context)
{
context.ActionArguments["param"] = this.greetingService.Greet("Dr. No");
}
publicvoid OnActionExecuted(ActionExecutedContext context)
{ }
}
应用它使用 TypeFilterAttribute。
[TypeFilter(typeof(GreetingTypeFilter))]
public IActionResult GreetType1(string param)
你也可以从TypeFilterAttribute继承 ,然后在没有TypeFilter的情况下 使用,
publicclass GreetingTypeFilterWrapper : TypeFilterAttribute
{
public GreetingTypeFilterWrapper() : base(typeof(GreetingTypeFilter))
{ }
}
[GreetingTypeFilterWrapper]
public IActionResult GreetType2(string param)
更多精彩文章请关注我们的微信公众号FocusDotCore:

基础教程:ASP.NET Core 2.0 MVC筛选器的更多相关文章
- ASP.NET Core 2.0 MVC项目实战
一.前言 毕业后入职现在的公司快有一个月了,公司主要的产品用的是C/S架构,再加上自己现在还在学习维护很老的delphi项目,还是有很多不情愿的.之前实习时主要是做.NET的B/S架构的项目,主要还是 ...
- ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现
from:https://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/ 代码生成工具: https ...
- ASP.NET Core 基础教程 - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core 基础教程 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 是对 ASP.NET 有重大意义的一次重新设计.本章节我们将介绍 A ...
- asp.net core 3.0 MVC JSON 全局配置
asp.net core 3.0 MVC JSON 全局配置 System.Text.Json(default) startup配置代码如下: using System.Text.Encodings. ...
- ASP.NET Core 3.0 gRPC 拦截器
目录 ASP.NET Core 3.0 使用gRPC ASP.NET Core 3.0 gRPC 双向流 ASP.NET Core 3.0 gRPC 拦截器 一. 前言 前面两篇文章给大家介绍了使用g ...
- asp.net Core 2.0 MVC为Controller或Action添加定制特性实现登录验证
前言:最近在倒腾 微软的新平台 asp.net Core 2.0,在这个过程中有些东西还是存在差异.下面是我在学习过程的一点笔记.有不妥之处,望各位大虾指正! 一.先创建一个控制器继承于Control ...
- 基础教程:视图中的ASP.NET Core 2.0 MVC依赖注入
问题 如何在ASP.NET Core MVC Views中注入和使用服务. 解 更新 启动 类来为MVC添加服务和中间件. 添加一项服务 添加一个Controller,返回 ViewResult. 添 ...
- ASP.NET Core 5.0 MVC中的 Razor 页面 介绍
Razor 是一个用于将基于服务器的代码嵌入到网页中的标记语法. Razor语法由 Razor 标记.c # 和 HTML 组成. 通常包含 Razor 的文件的扩展名 cshtml Razor 语法 ...
- ASP.Net Core 5.0 MVC 配置文件读取,Startup 类中ConfigureServices 方法、Configure 方法的使用
配置文件读取 1. 新建FirstController控制器 在appsettings文件内容替换成以下代码 { "Position": { "Title": ...
随机推荐
- 简单Elixir游戏服设计-创建玩家模型
删除model.ex 创建玩家模型 player.ex, 简单化,只有唯一标识,昵称,金币,够用了. 选择 map 代表数据,是为了扩展数据结构,方便增加功能.struct也是可以的. add_num ...
- 学习如何看懂SQL Server执行计划——基本知识篇
一.基本概念 1.数据的读取 页(page)是SQL SERVER可以读写的最小I/O单位.即使只需访问一行,也要把整个页加载到缓存之中,再从缓存中读取数据.物理读取是从磁盘上读取,逻辑读取是从缓存中 ...
- Java中Math.round()函数
Math.round(11.5) = 12; Math.round(-11.5) = -11; Math.round()函数是求某个数的整数部分,且四舍五入.
- linux下rename用法--批量重命名
Linux的rename 命令有两个版本,一个是C语言版本的,一个是Perl语言版本的,早期的Linux发行版基本上使用的是C语言版本的,现在已经很难见到C语言版本的了, 由于历史原因,在Perl语言 ...
- c# datetime与 timeStamp(unix时间戳) 互相转换
/// <summary> /// Unix时间戳转为C#格式时间 /// </summary> /// <param name="timeStamp" ...
- 设置QT应用程序图标方法(Windows下)
学习笔记,言简意赅. 1- 新建文本文件,编辑输入 IDI_ICON1 ICON DISCARDABLE "./image/WindowIco.ico" 注意: ...
- 03Vue事件
Vue提供了事件的绑定,方法写在methods对象中. 绑定dom中有两种方法: 方法一:v-on:click/dblclcick/mouseOver/mouseOut="方法名" ...
- Archlinux 安装小计
前阵子Fedora太不稳定,几乎不能正常使用了,同时也对版本形式的linux每次升级后各种扫尾和清扫工作感到有点厌倦,心里也非常想体验一下linux的滚动发行版,所以下定决心要干掉fedora,主流的 ...
- vux 组件打造手机端项目
其实,我用vux组件的过程是这样的,哇!太方便了!!功能好全!!太简单了!!然后,就各种"跳坑".以下排坑环节. 1.安装vux:cnpm i -S vux; 比较顺利吧. 2 ...
- iOS开发从申请账号到上线APP Store步骤
1.developer.apple.com 申请开发者账号 2.根据API Cloud创建证书: http://docs.apicloud.com/Dev-Guide/iOS-License-Appl ...