MVC攔截器,MVC過濾器,MVC ActionFilterAttribute攔截器過濾器,OnActionExecuting

來源:互聯網
上載者:User

標籤:mvc攔截器   mvc過濾器   mvc actionfilterattribute攔截器過濾器   onactionexecuting   

MVC實現攔截過濾器,過濾字串及實體類和動態修改資料,部分過濾和全部過濾:

#region

using System;

using System.Collections.Generic;

using System.Linq;

using System.Reflection;

using System.Security.Policy;

using System.Text;

using System.Web;

using System.Web.Mvc;

using System.Reflection;



namespace SaaS.Admin.Base

{

    /// <summary>

    /// 全域過濾器

    /// </summary>

    public class CustomerFilterAttribute:ActionFilterAttribute

    {

        /// <summary>

        /// 檢查是否需要過濾

        /// </summary>

        public bool IsCheck { get; set; }//是否需要過濾標記

        /// <summary>

        /// 在執行操作Action方法前執行調用

        /// </summary>

        /// <param name="filterContext"></param>

        public override void OnActionExecuting(ActionExecutingContext filterContext)

        {

            base.OnActionExecuting(filterContext);


            #region 檢查是否需要攔截過濾【不需要檢查過濾】

            if (!IsCheck)

            {

                return;//不需要過濾

            }

            #endregion

            var parameters = filterContext.ActionDescriptor.GetParameters();

            foreach (var parameter in parameters)

            {

                if (parameter.ParameterType == typeof(string))

                {

                    //擷取字串參數原值

                    var orginalValue = filterContext.ActionParameters[parameter.ParameterName] as string;

                    //使用過濾演算法處理字串

                    if (!string.IsNullOrEmpty(orginalValue) && orginalValue!="")

                    {

                        var filteredValue = HtmlEscapeCode(orginalValue);

                        ////將處理後值賦給參數

                        filterContext.ActionParameters[parameter.ParameterName] = filteredValue;

                    }


                }

                else if (parameter.ParameterName =="model")

                {

                    //擷取字串參數原值

                    var value = filterContext.ActionParameters[parameter.ParameterName];


                    if (value.GetType().IsClass && value.GetType().Name != "String")//檢查是否是類,並且不是字串類型

                    {


                        object objClass = value;//擷取字串參數原值

                        PropertyInfo[] infos = objClass.GetType().GetProperties();//擷取原對象的所有公用屬性


                        #region 動態建立新執行個體【動態建立新的實體類執行個體】

                        System.Type tt = System.Type.GetType(value.ToString());//擷取指定名稱的類型

                        object ff = Activator.CreateInstance(tt, null);//建立指定類型執行個體

                        PropertyInfo[] fields = ff.GetType().GetProperties();//擷取指定對象的所有公用屬性


                        object obj = Activator.CreateInstance(tt, null);//建立新指定類型的執行個體【動態建立新的執行個體】

                        #endregion


                        foreach (PropertyInfo info in infos)

                        {

                            if (info.CanRead)

                            {

                                //Console.WriteLine(info.Name + "=" + info.GetValue(objClass, null));


                                if (info.PropertyType.Name == "String") 

                                {

                                    //擷取值

                                    string orginalValue =Convert.ToString(info.GetValue(objClass, null));

                                    if (!string.IsNullOrEmpty(orginalValue) || orginalValue!="")

                                    {

                                        //檢查過濾特殊字元

                                        var filteredValue = HtmlEscapeCode(orginalValue);

                                        //將處理後值賦給參數

                                        info.SetValue(obj, filteredValue, null);

                                        //給實體物件賦新值

                                        filterContext.ActionParameters[parameter.ParameterName] = obj;

                                    }

                                }

                                else

                                {

                                    object orginalValue = info.GetValue(objClass, null);//擷取值

                                    info.SetValue(obj, orginalValue,null);//給對象賦新值

                                    filterContext.ActionParameters[parameter.ParameterName] = obj;//給實體類對象賦值

                                }

                            }

                        }


                    }

                }


            }


        }


        /// <summary>

        /// 在執行操作Action方法後執行調用

        /// </summary>

        /// <param name="filterContext"></param>

        public override void OnActionExecuted(ActionExecutedContext filterContext)

        {

            base.OnActionExecuted(filterContext);

            var controllerName = filterContext.RouteData.Values["controller"];

            var actionName = filterContext.RouteData.Values["action"];

        }


        //過濾關鍵字

        public string HtmlEscapeCode(string html)

        {

            var strhtml = html.Replace("javascript", "")

                        .Replace("vbscript", "")

                        .Replace("jscript", "")

                        .Replace("script", "")

                        .Replace("eval", "")

                        .Replace("<", "<")

                        .Replace(">", ">")

                        .Replace("\‘", "'")

                        .Replace("\"", """)

                        .Replace("&", "&")

                        .Replace("#", "#");

            return strhtml;

        }


    }

}

#endregion


//以下是不需要過濾的Controllers

using SaaS.Contracts.SaaS.Intern.Dtos.BugDtos;

using SaaS.Framework.SharpArch.Repositorys;

using SharpArch.NHibernate.Web.Mvc;

using SaaS.Models.Domain.Enums;

using SaaS.Models.Framework.Utility;

using SaaS.Framework.Collections;


namespace SaaS.Admin.Controllers

{

    /// <summary>

    /// BUG單管理

    /// </summary>

    [CustomerFilter(IsCheck =false)]//不需要過濾標記

    public class BugController : AuthorizeBaseController

    {

        /// <summary>

        /// 建立BUG單管理建構函式(產生建構函式的快捷健:ctorf後按下enter健)

        /// </summary>

        private readonly IBugService _bugService;


        public BugController(IBugService bugService)

        {

            _bugService = bugService;

           

        }

    }

}


//以下是需要過濾的標記

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Web.Mvc;

using Microsoft.Practices.ServiceLocation;

using SaaS.Contracts.SaaS.Intern;

using SaaS.Framework.IIdentity;

using SaaS.Models.Domain.Enums;


namespace SaaS.Admin.Base

{

    /// <summary>

    /// 基礎Controller

    /// </summary>

    [CustomerFilter(IsCheck = true)]//過濾標籤

    public class BaseController : Controller

    {

        /// <summary>

        /// 彈出成功提示

        /// </summary>

        /// <param name="message">成功訊息</param>

        /// <param name="url">跳轉路徑</param>

        /// <returns></returns>

        protected ActionResult SuccessResult(string message, string url)

        {


            TempData["SuccessResult"] = message;

            return Redirect(url);

        }

    }

}

本文出自 “程式猿” 部落格,請務必保留此出處http://haihuiwei.blog.51cto.com/4789207/1957030

MVC攔截器,MVC過濾器,MVC ActionFilterAttribute攔截器過濾器,OnActionExecuting

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.