先介绍下什么是过滤器:ASP.NET MVC中的灭一个请求,都会分配给相应的控制器和对应的行为方法去处理,而在这些处理的前前后后如果想再加一些额外的逻辑处理,这时就用到了过滤器。

MVC支持的过滤器有四种:Authorization(授权)、Action(行为)、Result(结果)、Exception(异常)

默认实现的过滤器如下:

一、授权过滤器

给Index页面,添加授权过滤器,只有当用户名为admin1和admin,密码是123456时,才可以访问index页面。

1.无参数的授权过滤器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Authorize]
public ActionResult Index()
{
    return View();
}
 
public ActionResult Login(LoginModel login)
{
    if ((login.UserName == "admin1" || login.UserName == "admin") && login.Password == "123456")
    {
        FormsAuthentication.SetAuthCookie(login.UserName, false);
 
        return Redirect("/Home/Index");
    }
 
    return View();
}

  此时,我们执行捷星程序,会发现报出无授权的错误,如下

这是由于Web.Config 中缺少如下代码:

1
2
3
<authentication mode="Forms">
      <forms loginUrl="~/Home/Login" timeout="1"/>
</authentication>

  此时,再次执行则会跳转至登录界面。

2.有参数的授权过滤器

[Authorize(Users = "admin,admin1")],可以实现和上面无参相同的功能

[Authorize(Users = "admin")],此时,只有UserName为amin时,才会跳转至index页面。

二、HandleError过滤器

1、MVC默认错误页面

定义一个界面抛出异常,此时会进去MVC默认的错误页面,即Views/Shared下的Error.cshtml

1
2
3
4
5
6
//处理错误过滤器HandleError
[HandleError(ExceptionType = typeof(Exception))]
public ActionResult ThrowError()
{
    throw new Exception("this is ThrowErrorLogin Action Throw");
}

  执行结果如下:

2、自定义错误页面

自定义一个错误页面MyError.cshtml

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
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <title>MyErrorPage</title>
</head>
<body>
    <div>
        <p>
            There was a <b>@Model.Exception.GetType().Name</b>
            while rendering <b>@Model.ControllerName</b>'s
            <b>@Model.ActionName</b> action.
        </p>
        <p style="color:Red">
            <b>@Model.Exception.Message</b>
        </p>
        <p>Stack trace:</p>
        <pre style=" background-color:Orange">@Model.Exception.StackTrace</pre>
    </div>
</body>
</html>

  此时在方法前加上[HandleError(ExceptionType = typeof(Exception), View = "MyError")],则调用抛出异常的界面,则会跳转至我们自定义的错误界面

三、自定义过滤器

自定义过滤器需要继承ActionFilterAttribute抽象类,重写其中的方法。

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
public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter
    {
        //
        // 摘要:
        //     初始化 System.Web.Mvc.ActionFilterAttribute 类的新实例。
        protected ActionFilterAttribute();
 
        //
        // 摘要:
        //     在执行操作方法后由 ASP.NET MVC 框架调用。
        //
        // 参数:
        //   filterContext:
        //     筛选器上下文。
        public virtual void OnActionExecuted(ActionExecutedContext filterContext);
        //
        // 摘要:
        //     在执行操作方法之前由 ASP.NET MVC 框架调用。
        //
        // 参数:
        //   filterContext:
        //     筛选器上下文。
        public virtual void OnActionExecuting(ActionExecutingContext filterContext);
        //
        // 摘要:
        //     在执行操作结果后由 ASP.NET MVC 框架调用。
        //
        // 参数:
        //   filterContext:
        //     筛选器上下文。
        public virtual void OnResultExecuted(ResultExecutedContext filterContext);
        //
        // 摘要:
        //     在执行操作结果之前由 ASP.NET MVC 框架调用。
        //
        // 参数:
        //   filterContext:
        //     筛选器上下文。
        public virtual void OnResultExecuting(ResultExecutingContext filterContext);
    }

1、不带参数的自定义过滤器

这里定义一个自定义的登录过滤器,用户名和密码为空,或者不为damin和123456,则会跳转至登录页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class CheckLogin: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpCookieCollection CookieCollect = System.Web.HttpContext.Current.Request.Cookies;
            if (CookieCollect["username"] == null || CookieCollect["password"] == null)
            {
                filterContext.Result = new RedirectResult("/Home/Login");
            }
            else
            {
                if (CookieCollect["username"].Value != "admin" && CookieCollect["password"].Value != "123456")
                {
                    filterContext.Result = new RedirectResult("/Home/Login");
                }
                
            }
        }
    }

  使用时只需要在方法名前加上[CheckLogin]即可。

2、带参数的自定义过滤器

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
public class ParamsFilter : ActionFilterAttribute
    {
        public string Message { get; set; }
 
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            filterContext.HttpContext.Response.Write("Action执行之前" + Message + "<br />");
        }
 
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            filterContext.HttpContext.Response.Write("Action执行之后" + Message + "<br />");
        }
 
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
            filterContext.HttpContext.Response.Write("返回Result之前" + Message + "<br />");
        }
 
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
            filterContext.HttpContext.Response.Write("返回Result之后" + Message + "<br />");
        }
    }

  这个自定一过滤器定义了一个string类型的参数,使用时在Action上加[ParamsFilter(Message = "test")]

四、如果一个Control中所有的Action都需要用到同一个过滤器,则可以直接在Control上面加此过滤器

MVC过滤器使用方法的更多相关文章

  1. asp.net MVC 过滤器使用案例:统一处理异常顺道精简代码

    重构的乐趣在于精简代码,模块化设计,解耦功能……而对异常处理的重构则刚好满足上述三个方面,下面是我的一点小心得. 一.相关的学习 在文章<精简自己20%的代码>中,讨论了异常的统一处理,并 ...

  2. MVC过滤器使用案例:统一处理异常顺道精简代码

    重构的乐趣在于精简代码,模块化设计,解耦功能……而对异常处理的重构则刚好满足上述三个方面,下面是我的一点小心得. 一.相关的学习 在文章<精简自己20%的代码>中,讨论了异常的统一处理,并 ...

  3. mvc过滤器学习(1)

    mvc 过滤器结构图 AuthorizeAttribute AuthorizeAttribute是IAuthorizationFilter的默认实现,添加了Authorize特性的Action将对用户 ...

  4. ASP.NET MVC 过滤器(一)

    ASP.NET MVC 过滤器(一) 前言 前面的篇幅中,了解到了控制器的生成的过程以及在生成的过程中的各种注入点,按照常理来说篇幅应该到了讲解控制器内部的执行过程以及模型绑定.验证这些知识了.但是呢 ...

  5. ASP.NET MVC 过滤器(三)

    ASP.NET MVC 过滤器(三) 前言 本篇讲解行为过滤器的执行过程,过滤器实现.使用方式有AOP的意思,可以通过学习了解过滤器在框架中的执行过程从而获得一些AOP方面的知识(在顺序执行的过程中, ...

  6. ASP.NET MVC 过滤器(四)

    ASP.NET MVC 过滤器(四) 前言 前一篇对IActionFilter方法执行过滤器在框架中的执行过程做了大概的描述,本篇将会对IActionFilter类型的过滤器使用来做一些介绍. ASP ...

  7. ASP.NET MVC 过滤器(五)

    ASP.NET MVC 过滤器(五) 前言 上篇对了行为过滤器的使用做了讲解,如果在控制器行为的执行中遇到了异常怎么办呢?没关系,还好框架给我们提供了异常过滤器,在本篇中将会对异常过滤器的使用做一个大 ...

  8. MVC过滤器详解

    MVC过滤器详解   APS.NET MVC中(以下简称"MVC")的每一个请求,都会分配给相应的控制器和对应的行为方法去处理,而在这些处理的前前后后如果想再加一些额外的逻辑处理. ...

  9. ASP.NET MVC 过滤器详解

    http://www.fwqtg.net/asp-net-mvc-%E8%BF%87%E6%BB%A4%E5%99%A8%E8%AF%A6%E8%A7%A3.html 我经历了过滤器的苦难,我想到了还 ...

随机推荐

  1. Tcl 编译成tbc文件

    工具:tclpro1.4 下载地址:https://www.tcl.tk/software/tclpro/eval/1.4.html 永久license:  Version 1.4: 1094-320 ...

  2. Windows Server 2008 R2 /2012 修改密码策略

    今天建了域环境,在添加新用户的时候,发现用简单的密码时域安全策略提示密码复杂度不够,于是我就想在域安全策略里面把密码复杂度降低一点. 问题:    在“管理工具 >> 本地安全策略 > ...

  3. Android memory dump

    1.读取指定pid和内存地址的字符: #include <stdlib.h> #include <stdio.h> #include <string.h> #inc ...

  4. Linux环境下使用Android NDK编译c/c++生成可执行文件

    1.安装Android NDK至Linux(Lubuntu 16) 从网上下载 android-ndk-r13b-linux-x86_64.zip,本人将其解压至/home/guanglun/work ...

  5. 解决Table不继承父节点的属性的方法

    解决Table不继承父节点的属性的方法 发现table不继承父节点的属性. 解决方法:给html文件加上<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...

  6. C/C++程序中内存被非法改写的一个检测方法

    本文所讨论的“内存”主要指(静态)数据区.堆区和栈区空间(详细的布局和描述参考<Linux虚拟地址空间布局>一文).数据区内存在程序编译时分配,该内存的生存期为程序的整个运行期间,如全局变 ...

  7. How do I improve my English speaking skills in a very short time?

    You have asked some very important questions. I think the first step is to prioritize the issues: Yo ...

  8. UHF RFID,高频RFID开发参考资料

    ISO18000-6C电子标签百科  http://baike.baidu.com/item/ISO18000-6C%E7%94%B5%E5%AD%90%E6%A0%87%E7%AD%BE/80500 ...

  9. FIFO使用技巧

    FPGA中,经常会用到FIFO来缓冲数据或者跨时钟传递数据. 1.Almost full & Almost empty 作为初学者,最开始使用FIFO的时候,对于它的理解,无非是配置好位宽.深 ...

  10. 0008 合并K个排序链表

    合并 k 个排序链表,返回合并后的排序链表.请分析和描述算法的复杂度. 示例: 输入: [   1->4->5,   1->3->4,   2->6 ] 输出: 1-&g ...