我有一个应用程序,它起初是一个小型Web表单项目,并且很快就变得非常庞大。我想记录每个触发的事件,并检查用户对指定操作的权限。
不是在每个事件中添加功能,我认为一个好方法是创建一个覆盖默认“System.Web.UI.Page”的基类,并检查基类中的每个事件调用。 / p>
以下是该类的代码:
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;
}
}
}
您可能会注意到它并不完整,因为我仍在研究此选项。我还没有找到一种方法来检索触发事件,以便我可以记录被调用的函数名称,并检查用户是否有权调用该函数。可能吗?即使是肮脏的黑客也会这样做。
答案 0 :(得分:0)
您可以使用PostSharp拦截事件,而不是覆盖默认的“System.Web.UI.Page”类。您可以查看以下文章以获取演练
PostSharp Principles: Day 11 – EventInterceptionAspect
您可以构建一个方面,在触发事件时调用自定义方法。使用自定义方法记录呼叫和访问检查。可以全局应用方面以使用多播来节省您的工作。
PostSharp Principles: Day 2 - Applying Aspects with Multicasting Part 1
PostSharp Principles: Day 2 - Applying Aspects with Multicasting Part 2