zoukankan      html  css  js  c++  java
  • ASP.NET MVC 过滤器开发与使用

    ASP.NET MVC 中给我们提供了内置的过滤器,通过过滤器,我们可以在控制器内的方法前后,添加必须的业务逻辑,如权限验证,身份验证,错误处理等。

    今天,我们主要介绍3个过滤器:OutputCacheAttribute,AuthorizeAttribute,HandleErrorAttribute。

    我们会根据这三个内置过滤器,分别举不同的例子进行解释说明。

    1. OutputCacheAttribute

    我们先看看源码:

    可以看出OutputCacheAttribute继承了ActionFilterAttribute,所以可以重写ActionFilterAttribute的方法OnActionExecuting等,

    类中有CacheProfile,Duration,VaryByParam几个属性,下面我们看一下用法。添加如下代码:

    [OutputCache(Duration=10)]
            public ActionResult OutputCache()
            {
                ViewData["TimeCache"] = "当前时间是:" + DateTime.Now.ToLongTimeString();
                return View();
            }

    打开浏览器,可以看到,不断刷新,每10秒就会更新一次:

    当然,也可以写在页面上,在页面添加代码:

    <%@ OutputCache Duration="10" VaryByParam="None" %>

    如下面代码:

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
    <%@ OutputCache Duration="10" VaryByParam="None" %>
    <!DOCTYPE html>
    
    <html>
    <head runat="server">
        <meta name="viewport" content="width=device-width" />
        <title>OutputCache</title>
    </head>
    <body>
        <div>
            <%=ViewData["TimeCache"] %>
        </div>
    </body>
    </html>

    或者使用CacheProfile,代码如下:

     [OutputCache(CacheProfile = "testProfile")]
            public ActionResult OutputCache()
            {
                ViewData["TimeCache"] = "当前时间是:" + DateTime.Now.ToLongTimeString();
                return View();
            }

    在web.config添加如下配置:

    <system.web>
        <caching>
          <outputCacheSettings>
            <outputCacheProfiles>
              <add name="testProfile" duration="10" varyByParam="*" />
            </outputCacheProfiles>
          </outputCacheSettings>
        </caching>
     </system.web>

    2. AuthorizeAttribute

    AuthorizeAttribute类的作用,主要是为页面指定操作用户和角色。

    我们假设以Session作为页面管理权限,新建一个CustomAuthorize类,添加如下代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MvcMobileDMS.App_Start
    {
        public class CustomAuthorize : AuthorizeAttribute
        {
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                //假设以Session作为判断页面权限
                if (filterContext.HttpContext.Session["temp"] == null)
                {
                    filterContext.HttpContext.Response.Redirect("~/dms/logon");
                }
                base.OnAuthorization(filterContext);
                
            }
        }
    }

    再在控制器中的方法添加如下代码:

    [MvcMobileDMS.App_Start.CustomAuthorize]
            public ActionResult Authorize()
            {
    
                return View();
            }

    即可进行权限检查。

    3. HandleErrorAttribute

    HandleErrorAttribute特性主要用于处理由操作引发的错误。在实际操作中我们可以继承HandleErrorAttribute类,并重写OnException方法来进行错误记录。

    首先,我们新建一个错误页:

     public ActionResult error()
            {
                return View();
            }
    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
    
    <!DOCTYPE html>
    
    <html>
    <head runat="server">
        <meta name="viewport" content="width=device-width" />
        <title>error</title>
    </head>
    <body>
        <div>
            Sorry.an error occoured.
        </div>
    </body>
    </html>

    并添加错误处理类ErrorHandle继承自HandleErrorAttribute,代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MvcMobileDMS.App_Start
    {
        public class ErrorHandle : HandleErrorAttribute
        {
            public override void OnException(ExceptionContext Context)
            {
                HttpContext.Current.Response.Redirect("~/dms/error");
                base.OnException(Context);
            }
        }
    }

    在DMS控制器新增一个方法EceptionThrow,并加上过滤器ErrorHandle,代码如下:

    [MvcMobileDMS.App_Start.ErrorHandle]
            public ActionResult EceptionThrow()
            {
                throw new ArgumentNullException("filterContext");           
            }

    下面,我们打开浏览器,输入地址:http://localhost:7449/dms/EceptionThrow,显示如下:

    当EceptionThrow()方法抛出错误时,ErrorHandle过滤器触发OnException方法,跳转到error页面。

    由此可见,我们可以通过HandleErrorAttribute过滤器,处理各种Exception,并使用自定义方法进行处理。

    以上,希望能对您有所帮助O(∩_∩)O哈哈~

  • 相关阅读:
    【转】数据安全保护之访问控制技术
    WebRTC介绍及简单应用
    【转】Weblogic的集群
    【转载】桥接Microsoft Word和浏览器
    http Content-type对照表
    CentOS7.1下JDK+Tomcat应用环境搭建
    关于silverlight5 打印功能收集
    【转】2014年25款最好的jQuery插件
    lesson11
    lesson 9
  • 原文地址:https://www.cnblogs.com/JinvidLiang/p/4660200.html
Copyright © 2011-2022 走看看