62,046
社区成员
发帖
与我相关
我的任务
分享
class PageLoggerModule : IHttpModule //实现IHttpModule接口
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
//在这里实现具体代码
HttpApplication app = (HttpApplication)sender;
HttpContext ctx = app.Context;
//acquire session state
string userId = "Not Registered";
if (ctx.Session != null && ctx.Session["userId"] != null)
{
userId = ctx.Session["userId"].ToString();
}
//acquire request string
string funcId = "Init funcId";
if (ctx.Request.QueryString["funcId"] != null)
{
funcId = ctx.Request.QueryString["funcId"].ToString();
}
LogEntry log = new LogEntry(); // 这里是自定义的一个类,属性列表和数据库中的字段一致
log.DateTime = System.DateTime.Now;
log.IpAddress = ctx.Request.UserHostAddress;
log.MachineName = ctx.Request.UserHostName;
log.UserId = userId;
log.FunctionId = funcId;
string logString = log.DateTime.ToString() + "<br/>"
+ log.UserId + "<br/>"
+ log.IpAddress + "<br/>"
+ log.MachineName + "<br/>"
+ log.FunctionId + "<br/>";
//you can add other codes here
ctx.Response.AppendHeader("Author", "Changyu Du");
ctx.Response.Write(logString);
}
}
//在Web.config中,System.Web节中增加一个HttpModule:
<httpModules>
<add name="PageLoggerHttpModule" type="PageLoggerHttpModule.PageLoggerModule,PageLoggerHttpModule"/>
</httpModules>
//新建一个普通的aspx页面,在页面加载时把用户信息保存到Session中,模拟一下项目应用中的情形:
protected void Page_Load(object sender, EventArgs e)
{
//Add userName into SESSION
if (Session["userId"] == null)
{
Session["userId"] = "1101";
}
else
{
Response.Write("SESSION :userId = "+Session["userId"].ToString());
}
}