检索事件名称和触发回发的控件,最好是将要调用的函数名称

本文关键字:函数 调用 事件 检索 控件 | 更新日期: 2023-09-27 18:06:53

我有一个应用程序,开始作为一个小的web表单项目,并迅速变得非常大。我想记录每个触发的事件,并检查指定操作的用户权限。

与其在每个事件中添加功能,我认为一个好方法是创建一个基类来覆盖默认的'System.Web.UI '。页'并检查基类中的每个事件调用。

下面是该类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test
{
    /// <summary>
    /// Summary description for BasePage
    /// </summary>
    public abstract class BasePage : System.Web.UI.Page
    {
        public BasePage()
        {
            // Adding functionality to the "on load" event of the base class (Page)
            base.Load += new EventHandler(BasePage_Load);
            base.Unload += new EventHandler(BasePage_Unload);
            base.LoadComplete += new EventHandler(BasePage_LoadComplete);
        }
        private void BasePage_Load(object sender, EventArgs e)
        {
            LogEverything();
            AccessCheck();
        }
        private void BasePage_LoadComplete(object sender, EventArgs e)
        {
            LogEverything();
            AccessCheck();
        }
        protected override void RaisePostBackEvent(System.Web.UI.IPostBackEventHandler sourceControl, string eventArgument)
        {
            LogEverything();
            base.RaisePostBackEvent(sourceControl, eventArgument);
        }

        private void BasePage_Unload(object sender, EventArgs e)
        {
            LogEverything();
        }
        private bool LogEverything()
        {
            string sRawUrl = HttpContext.Current.Request.RawUrl;
            string sQueryString = HttpContext.Current.Request.QueryString.ToString();
            string sPage = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
            string sHttpMethod = HttpContext.Current.Request.HttpMethod;
            string sUserAgent = HttpContext.Current.Request.UserAgent;
            string sUserAddress = HttpContext.Current.Request.UserHostAddress;
            string sEventTarget = HttpContext.Current.Request.Form["__EVENTTARGET"];
            string sEventArgument = HttpContext.Current.Request.Form["__EVENTARGUMENT"];
            string sEventValidation = HttpContext.Current.Request.Form["__EVENTVALIDATION"];
            // TODO: find the event that triggered the postback
            return Logging.append(Logging.logLevelType.Info, "Baseclass is here!");
        }
        private bool AccessCheck()
        {
            // enforce security here ...
            return true;
        }
    }
}

你可能会注意到,这是不完整的,因为我还在研究这个选项。我还没有找到一种方法来检索触发的事件,以便我可以记录被调用的函数名称,并检查用户是否有权调用该函数。这可能吗?

检索事件名称和触发回发的控件,最好是将要调用的函数名称

而不是覆盖默认的'System.Web.UI。类,你可以使用PostSharp拦截事件。您可以查看下面的文章以获得演练

PostSharp原则:第11天- EventInterceptionAspect

您可以构建一个方面,它将在事件触发时调用您的自定义方法。使用自定义方法记录呼叫和访问检查。方面可以全局应用,以节省您使用多播的一些工作。

PostSharp原则:第2天-多播应用第1部分

PostSharp原则:第2天-应用方面与组播第2部分