ASP.NET MVC 过滤器开发与使用

本文详细介绍了ASP.NET MVC中的三个内置过滤器:OutputCache用于缓存输出以提高效率;Authorize用于权限验证,确保用户具备执行特定操作的权限;HandleError用于捕获和处理异常,实现自定义错误页面展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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哈哈~

转载于:https://www.cnblogs.com/JinvidLiang/p/4660200.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值