ASP.NET全局应用程序类所有事件详解
在Asp.Net中一个全局应用程序类,就是程序中 Global.asax 这个文件,全局应用程序类中的内容不需要在每个页面手动添加应用,程序在执行时默认都会先执行 Global.asax 中的代码,一个应用程序只可以有一个 Global.asax 文件,下面我们详细解释 Global.asax 中的一些事件属性的使用方法。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace WebApplication1
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码。
// 程序第一次获得请求时,该方法被执行。
}
protected void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码。
// 该方法被调用,表示当前有一个新的会话产生了。
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
// 在新请求启动时允许的代码。
// 每一次请求都会触发该方法。
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码。
// 程序第一次获得请求时,该方法被执行。
}
protected void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码
// 获取异常信息并处理:HttpContext.Current.Server.GetLastError();
}
protected void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为InProc 时,才会引发 Session_End 事件。
// 如果会话模式设置为 StateServer 或 SQLServer,则不会引发该事件。
}
protected void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
}
}
}
应用:
Session_Start()方法:统计在线人数。
Application_BeginRequest()方法:屏蔽IP,防止盗链。对所以图片加水印。
Application_AuthenticateRequest()方法:验证方法。
Application_Error()方法:
补充:
1.取得当前请求url:HttpContext.Current.Request.Url
2.手动注销Session:HttpContext.Current.Session.Abandon()
3.向文件添加文本信息,若文件不存在,则先创建:File.AppendAllText("c:1.txt",DateTime.Now.ToString())
4.取得访问网站的请求的ip:HttpContext.Current.Request.UserHostAddress;
5.向页面打印输出:HttpContext.Current.Request.Write("已被屏蔽!");
6.打印输出结束要调用:HttpContext.Current.Request.End();
7.取得请求类型:HttpContext.Current.Request.ContentType
8.获取客户端上次请求的url信息:HttpContext.Current.Request.UrlReferrer; (说明:该属性是Uri类的实例。)
9.获取uri对象的域名:uri.Host;
(获取客户端上次请求的url的域名:HttpContext.Current.Request.UrlReferrer.Host;)
10.获取异常信息:HttpContext.Current.Server.GetLastError();
上一篇:无
下一篇:Asp.Net读写Cookie方法