AspNet MVC3中过滤器 + 实例

过滤器在请求管线注入额外的逻辑,提供简单优雅的方法实现横切点关注(AOP),例如日志,授权,缓存等应用.通过AOP可以减少在实际的业务逻辑中参杂过多非直接业务逻辑功能的代码,让某个行为或者动作更加专注于自身的功能逻辑,例如统计Action,专注于数据的统计分析而不要关注日志以及调用的身份验证和授权问题.


1.过滤器类型

AspNet MVC中包含三种常用的过滤器分别是:Action(行为过滤器) , Result(结果过滤器) ,Exception(异常过滤器)和Authorization(授权过滤器).

| --------------------------------------------------------------------------------------|

| 过滤器类型             |     对应接口                          |            描述                                 |

-----------------------------------------------------------------------------------------

| Authorization           IAuthorizationFilter               用于实现用户验证和对Action的访问授权,例如默认的Authorize过滤器

| Action                    IActionFilter                        用于对Action执行前后的逻辑控制,例如修改参数,返回数据controller

| Result                    IResultFilter                         用于修改视图向浏览器展现的结果,通过对ViewReuslt生成前后逻辑控制

| Exception               IExceptionFilter                    用于处理行为和结果的错误,日志的记录

过滤器的默认执行顺序为Authorization > Action > Result > Exception ,如果需要修改只执行的顺序可以通过修改Order属性来实现.


2. AspNet MVC提供的集中默认过滤器

a. Authorize 用户当前用户登录验证,通过匹配用户名和角色(roles)实现

b. ChildActionOnly 指定当前行为(Action)是某个请求的一部分。

c. OutputCache 控制页面数据的缓存

d. HandleError 页面访问的异常/错误处理,在页面或者行为数据错位时候可以导航到指定的错误页面


3.定制过滤器

用户定制过滤器主要需要实现或者重写一些方法比如:

实现途径有两种方式: 一种是通过继承ActionFilterAttribute或者AuthorizeFilterAttribute等类,然后重写对应的逻辑方法,还有一种就是如1中描述的,通过实现一些类似IActionFilter或者ResultFilter等接口来实现,第二种实现相对来说较底层.

例如要实现多某个行为Action的拦截,可以通过继承IActionFilter或者ActionFilterAttribute实现方法OnActionExecuting和OnActionExecuted在请求访问到达指定的Action前对请求进行处理和对访问后返回数据的处理

4.过滤器应用

这里主要演示对Action行为的拦截,一个是针对Action参数的拦截,判断访问请求数据是否包含敏感字眼一个通过action的身份授权验证

如果要直接在行为Action上使用类似属性那般在继承对应的接口时候还要继承类FilterAttribute

a. 敏感字眼的过滤

主要实现OnActionExecuting方法,在请求达到action前先对请求的参数进行过滤,通过指定的过滤算法将参数信息进行过滤替换

   public class CustomActionFilterAttribute : IActionFilter {
public void OnActionExecuted(ActionExecutedContext filterContext) { } public void OnActionExecuting(ActionExecutingContext filterContext) {
//对参数的过滤,例如处理一些比较敏感的信息
//s1: 获取参数信息 ,得到参数的个数以及每个参数的类别
filterContext.ActionDescriptor.GetParameters();
//s2: 获取参数值,返回一个字典
//parameterValue 参数值 , parameterName 参数名
var parameterValue = filterContext.ActionParameters[parameterName];
//s3: 敏感信息过滤
// 过滤算法 // 过滤后赋值
filterContext.ActionParameters[parameterName] = newParameterValue; }
}

b. 访问授权

  public class AuthenticationFilterAttribute:IActionFilter{
public void OnActionExecuted(ActionExecutedContext filterContext) {
//throw new NotImplementedException();
} public void OnActionExecuting(ActionExecutingContext filterContext) {
// 未认证直接重定向到登录页面,并设置登录成功后的目标URL
if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
string redirect_string = filterContext.HttpContext.Request.Url.AbsolutePath;
//设置登录成功后转向的URL,格式例如:http://xxx.xxx/login.aspx?ReturnUrl=www.swzsoft.cn
string returnUrl = string.Format("?ReturnUrl={0}", redirect_string);
//重定向到登录的URL后面的returnUrl参数用于登录通过后的页面跳转
string loginUrl = System.Web.Security.FormsAuthentication.LoginUrl + returnUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}

基于角色的访问授权

    public class BaseOnRolesAuthenticationFilterAttribute:FilterAttribute, IActionFilter{
public void OnActionExecuted(ActionExecutedContext filterContext) {
//throw new NotImplementedException();
} public string Role{get;set;}
public BaseOnRolesAuthenticationFilterAttribute(string role){
Role = role;
} public void OnActionExecuting(ActionExecutingContext filterContext) {
if (!string.IsNullOrEmpty(Role)) {
// 未认证直接重定向到登录页面,并设置登录成功后的目标URL
if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
string redirect_string = filterContext.HttpContext.Request.Url.AbsolutePath;
//设置登录成功后转向的URL,格式例如:http://xxx.xxx/login.aspx?ReturnUrl=www.swzsoft.cn
string returnUrl = string.Format("?ReturnUrl={0}", redirect_string);
//重定向到登录的URL后面的returnUrl参数用于登录通过后的页面跳转
string loginUrl = System.Web.Security.FormsAuthentication.LoginUrl + returnUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
else {
bool bIsAuthorized = filterContext.HttpContext.User.IsInRole(this.Role);
if (!bIsAuthorized) {
throw new UnauthorizedAccessException("");
}
}
}else{
throw new InvalidOperationException("");
}
}
} // 应用,针对某个Controller的某个Action
[BaseOnRolesAuthenticationFilter("Andy")]
public ActionResult AdminIndex() {
ViewBag.Msg = "Amdin INdex";
return View();
}
 
 

AspNet MVC3中过滤器 + 实例的更多相关文章

  1. AngularJS 表达式中添加过滤器实例

    过滤器可以通过一个管道字符(|)和一个过滤器添加到表达式中 历练实例: <!DOCTYPE html><html><head><meta http-equiv ...

  2. AspNet MVC中各种上下文理解

    0  前言 AspNet MVC中比较重要的上下文,有如下: 核心的上下文有HttpContext(请求上下文),ControllerContext(控制器上下文) 过滤器有关有五个的上下文Actio ...

  3. ASP.NET MVC3中Controller与View之间的数据传递总结

    一.  Controller向View传递数据 1.       使用ViewData传递数据 我们在Controller中定义如下: ViewData["Message_ViewData& ...

  4. ASP.NET MVC3中Controller与View之间的数据传递

    在ASP.NET MVC中,经常会在Controller与View之间传递数据,因此,熟练.灵活的掌握这两层之间的数据传递方法就非常重要.本文从两个方面进行探讨: 一.  Controller向Vie ...

  5. flask中过滤器的使用

    过滤器 过滤器的本质就是函数.有时候我们不仅仅只是需要输出变量的值,我们还需要修改变量的显示,甚至格式化.运算等等,而在模板中是不能直接调用 Python 中的某些方法,那么这就用到了过滤器. 使用方 ...

  6. 黑马vue---31-32、vue过滤器实例

    黑马vue---31-32.vue过滤器实例 一.总结 一句话总结: vue内部的东西,无论是过滤器还是组件,都是键值对的方式 1.过滤器的定义语法? Vue.filter('过滤器的名称', fun ...

  7. 【5min+】AspNet Core中的全局异常处理

    系列介绍 [五分钟的dotnet]是一个利用您的碎片化时间来学习和丰富.net知识的博文系列.它所包含了.net体系中可能会涉及到的方方面面,比如C#的小细节,AspnetCore,微服务中的.net ...

  8. 关于Javascript中通过实例对象修改原型对象属性值的问题

    Javascript中的数据值有两大类:基本类型的数据值和引用类型的数据值. 基本类型的数据值有5种:null.undefined.number.boolean和string. 引用类型的数据值往大的 ...

  9. MVC3中如何输出富文本

    MVC3中如何输出富文本 在网站的文本输出中,经常会将DB里的文本输出到页面上. 一般来说是直接利用MVC3中的ViewBag将文本带到前台并表示, 或是是直接以<%:model.data%&g ...

随机推荐

  1. MVC推荐教程和文章列表

    着手Getting Started Getting Started with ASP.NET MVC 5 (共11部分) Pluralsight ASP.NET MVC 5 Fundamentals( ...

  2. MessageDigest简要

    本文博客原 參考文章:http://blog.sina.com.cn/s/blog_4f36423201000c1e.html 一.概述 java.security.MessageDigest类用于为 ...

  3. Extjs4.1MVC详细解释

    :http://xiebaochun.github.io/ app.js [javascript] view plaincopyprint? Ext.onReady(function(){ Ext.Q ...

  4. java_tomcat_the_APR based Apache Tomcat 小喵咪死活启动报错_临时方案

    报错信息如下: 信息: The APR based Apache Tomcat Native library which allows optimal performance in productio ...

  5. mysql 数据库插入语句之insert into,replace into ,insert ignore

    近期才发现mysql的插入语句竟然有如此多的使用方法,这里拿来分享一下. ①关于insert into : insert into table_name values(); insert into t ...

  6. Self referencing loop detected with type

    json.net namespace EFDAL{    using System;    using System.Collections.Generic;    using Newtonsoft. ...

  7. GetDirectories 出错的解决方法

    我想找到D盘里面所有 "*.pst文件,类似 windows 下的磁盘搜索功能, using System.IO; Directory.GetFiles(@"d:\", ...

  8. [Cocoa]深入浅出 Cocoa 之消息

    深入浅出 Cocoa 之消息    罗朝辉(http://blog.csdn.net/kesalin) 转载请注明出处 在入门级别的ObjC 教程中,我们常对从C++或Java 或其它面向对象语言转过 ...

  9. Linux server关闭自己主动

    公司linux server发生错误.mysql server没有理由关闭,我找不到理由.Version: '5.6.13-enterprise-commercial-advanced' socket ...

  10. Android DES AES MD5加密

    AES加密: <span style="font-size:18px;">package com.example.encrypdate.util; import jav ...