標籤:blog http os io ar strong 檔案 art div
ASP.NET全域應用程式類引自老Man的部落格http://shijiaqi1066.iteye.com/blog/1728603這個儲存到自己的部落格裡邊方便以後學習查看
通用檔案
建立通用檔案
Visual Studio 【添加新項】-->【Web】-->【全域應用程式類】
產生Global類。
一個webapplication只能有一個全域應用程式類。如果建立的是否發現沒有【全域應用程式類】,則表示已經該類已經存在,如果需要建立,則先刪除舊的,再建立。
Global類:
C#代碼
- 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全域應用程式類