龙空技术网

.NET MVC使用Action过滤器处理方法

自由的孔雀 251

前言:

目前朋友们对“mvc action过滤器”都比较看重,小伙伴们都需要了解一些“mvc action过滤器”的相关文章。那么小编在网络上搜集了一些关于“mvc action过滤器””的相关文章,希望小伙伴们能喜欢,兄弟们快快来了解一下吧!

Action过滤器在动作方法之前及之后运行,Result过滤器在动作结果被执行之前和之后运行。

1、Action过滤器

在ASP.NET MVC中创建MvcApp项目,创建文件夹Filter,然后新建类MyActionFilterAttribute(为了遵循默认的约定,名称以Attribute结尾),继承自ActionFilterAttribute类。ActionFilterAttribute类有如下4个方法。

using System; namespace System.Web.Mvc{    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]    public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter    {         protected ActionFilterAttribute();         public virtual void OnActionExecuted(ActionExecutedContext filterContext);         public virtual void OnActionExecuting(ActionExecutingContext filterContext);         public virtual void OnResultExecuted(ResultExecutedContext filterContext);         public virtual void OnResultExecuting(ResultExecutingContext filterContext);    }}

实现MyActionFilterAttribute类:

using System;using System.Web.Mvc; namespace MvcApp.Filter{    public class MyActionFilterAttribute : ActionFilterAttribute    {        public override void OnActionExecuting(ActionExecutingContext filterContext)        {            //1、获取请求的类名和方法名            string strController = filterContext.RouteData.Values["controller"].ToString();            string strAction = filterContext.RouteData.Values["action"].ToString();             //2、用另一种方式获取请求的类名和方法名            string strController2 = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;            string strAction2 = filterContext.ActionDescriptor.ActionName;             filterContext.HttpContext.Response.Write("控制器:" + strController + "<br/>");            filterContext.HttpContext.Response.Write("控制器:" + strController2 + "<br/>");            filterContext.HttpContext.Response.Write("Action:" + strAction + "<br/>");            filterContext.HttpContext.Response.Write("Action:" + strAction2 + "<br/>");             filterContext.HttpContext.Response.Write("Action执行前:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff") + "<br/>");            base.OnActionExecuting(filterContext);        }         public override void OnActionExecuted(ActionExecutedContext filterContext)        {            filterContext.HttpContext.Response.Write("Action执行后:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff") + "<br/>");            base.OnActionExecuted(filterContext);        }    }}

对于过滤器,我们可以把它们加在3个地方,一个是控制器上面(控制器下面的所有Action),一个是Action上面(指定标识的Action),另一个就是全局位置(所有控制器中的Action)。这里只演示在Action上面和Home控制器中:

[MyActionFilter]public ActionResult Index(){    return View();}

2、Result过滤器

新建MyResultFilterAttribute类,继承ActionFilterAttribute:

using System;using System.Web.Mvc; namespace MvcApp.Filter{    public class MyResultFilterAttribute : ActionFilterAttribute    {        /// <summary>        /// 加载“视图”前执行        /// </summary>        /// <param name="filterContext"></param>        public override void OnResultExecuting(ResultExecutingContext filterContext)        {            filterContext.HttpContext.Response.Write("加载视图前执行 OnResultExecuting" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff") + "<br/>");            base.OnResultExecuting(filterContext);        }         /// <summary>        /// 加载“视图”后执行        /// </summary>        /// <param name="filterContext"></param>        public override void OnResultExecuted(ResultExecutedContext filterContext)        {            filterContext.HttpContext.Response.Write("加载视图后执行 OnResultExecuted" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff") + "<br/>");            base.OnResultExecuted(filterContext);        }    }}

这里把MyResultFilter过滤器加在控制器上面,相当于给Home控制器中的所有的Action方法添加了MyResultFilter过滤器。

using MvcApp.Filter;using System.Web.Mvc; namespace MvcApp.Controllers{    [MyResultFilter]    public class HomeController : Controller    {        [MyActionFilter]        public ActionResult Index()        {            return View();        }    }}

运行结果,如下图:

示例:使用Action过滤器,实现操作日志的记录功能。

在Models目录下创建OperateLogModel.cs(操作日志实体类):

using System;using System.Collections.Generic;using System.Linq;using System.Web; namespace MvcApp.Models{    /// <summary>    /// 操作日志实体类    /// </summary>    public class OperateLogModel    {        /// <summary>        /// 控制器名称        /// </summary>        public string ControllerName { get; set; }         /// <summary>        /// Action名称        /// </summary>        public string ActionName { get; set; }         /// <summary>        /// 功能模块        /// </summary>        public string FunctionalModule { get; set; }         /// <summary>        /// 操作类型        /// </summary>        public string OperationType { get; set; }         /// <summary>        /// 操作时间        /// </summary>        public DateTime OperationDate { get; set; }         /// <summary>        /// 路径        /// </summary>        public string Path { get; set; }         /// <summary>        /// 请求参数        /// </summary>        public string Params { get; set; }    }}

创建Filter目录,并在该目录下创建OperateLogAttribute类,继承ActionFilterAttribute类:

using MvcApp.Models;using Newtonsoft.Json;using System;using System.IO;using System.Text;using System.Web;using System.Web.Mvc; namespace MvcApp.Filter{    /// <summary>    /// 操作日志    /// </summary>    public class OperateLogAttribute : ActionFilterAttribute    {        /// <summary>        /// 功能模块        /// </summary>        public string FunctionalModule { get; set; }         /// <summary>        /// 操作类型        /// </summary>        public string OperationType { get; set; }         /// <summary>        /// 记录请求日志        /// </summary>        public override void OnActionExecuting(ActionExecutingContext filterContext)        {            //创建操作日志实体类            OperateLogModel requestLog = new OperateLogModel();            requestLog.ControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;            requestLog.ActionName = filterContext.ActionDescriptor.ActionName;            requestLog.FunctionalModule = this.FunctionalModule;            requestLog.OperationType = this.OperationType;            requestLog.OperationDate = DateTime.Now;            requestLog.Path = filterContext.RequestContext.HttpContext.Request.Path;            requestLog.Params = GetStrPatams(filterContext.RequestContext.HttpContext.Request);             //记录日志            string logJson = JsonConvert.SerializeObject(requestLog);            WriteLog(logJson);        }         /// <summary>        /// 获取字符串参数        /// </summary>        public string GetStrPatams(HttpRequestBase theRequest)        {            string result = "";            string url = theRequest.Url.ToString();             string method = theRequest.HttpMethod;            if (method == "GET")            {                result = theRequest.QueryString.ToString();            }            else if (method == "POST")            {                result = theRequest.Form.ToString();            }             //if (result == "")            //{            //    result = theRequest.Params.ToString();            //}             if (result.Length > 0)            {                result = HttpUtility.UrlDecode(result, Encoding.UTF8);            }             return result;        }         /// <summary>        /// 写入日志        /// </summary>        public void WriteLog(string message)        {            string path = AppDomain.CurrentDomain.BaseDirectory + "/MyLog.txt";            using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))            {                sw.Flush();                sw.WriteLine("时间:" + DateTime.Now);                sw.WriteLine("内容:" + message);                sw.WriteLine("-------------------------");            }        }    }}

创建OrderController.cs(订单控制器),编写新增订单方法,并在该方法上添加OperateLog特性:

using MvcApp.Filter;using MvcApp.Models;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace MvcApp.Controllers{    /// <summary>    /// 订单控制器    /// </summary>    public class OrderController : Controller    {        /// <summary>        /// 新增订单        /// </summary>        [OperateLog(FunctionalModule = "订单业务", OperationType = "新增")]        public bool AddOrder(string orderName, decimal price)        {            return true;        }    }}

————————————————

原文链接:

标签: #mvc action过滤器