这几天接到一个用户需求,需要为一个在运行的基于Asp.Net Web Form的老系统增加审计日志。对于用户访问的界面上的每个按钮,都需要记录下来访问的用户名、时间、IP地址。我们不能修改这个系统,最后决定采用HttpHandler处理这个问题,示例代码如下:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Plat.LogHandler
{
public class Handler : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true);
try
{
IHttpHandler handler = factory.GetHandler(context, requestType, url, pathTranslated);
if (handler is Page)
{
Page page = handler as Page;
page.PreRenderComplete += new EventHandler(PreRenderComplete);
}
return handler;
}
catch (Exception ex)
{
throw ex;
}
}
public void ReleaseHandler(IHttpHandler handler)
{
}
private void PreRenderComplete(object sender,EventArgs e)
{
var page = sender as Page;
if (page != null && page.IsPostBack)
{
var btn = getPostBackControlName(page);
if (btn != null)
{
WriteLog(page.Title, btn.Text , btn.ID);
}
}
}
private Button getPostBackControlName(Page page)
{
Control c = null;
foreach (string ctl in page.Request.Form)
{
c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button )
{
return c as Button;
}
}
return null;
}
}
}
还需要在Web.config中进行配置,在system.web中:
<httpHandlers>
<add path="*.aspx" verb="*" type="Plat.LogHandler.Handler" />
</httpHandlers>
在system.webserver中
<handlers>
<add path="*.aspx" verb="*" type="Plat.LogHandler.Handler" name="logHandler" />
</handlers>
采用这种方法,在没有修改原有系统代码的情况下,满足了用户的需求。