在每一個頁面的aspx.cs檔案中都要寫代碼檢查使用者是否已登入,麻煩。這樣子來做比較好。
先建一個測試用解決方案吧,WebApplication1
建立一個類,就叫LoginModule好了,繼承 IHttpModule 介面,內容差不多是這樣子:
1using System;
2using System.Web;
3using System.Web.Handlers ;
4
5namespace WebApplication1
6{
7 /**//// <summary>
8 /// LoginModule 的摘要說明。
9 /// </summary>
10 public class LoginModule : IHttpModule
11 {
12 public LoginModule()
13 {
14 //
15 // TODO: 在此處添加建構函式邏輯
16 //
17 }
18
19 private void context_AcquireRequestState(object sender, EventArgs e)
20 {
21 HttpContext context = HttpContext.Current;
22 try
23 {
24 //把不需要驗證的Handler加在這裡
25 if (context.Handler is TraceHandler)
26 {
27 return;
28 }
29 if(context.Session["Session_User"] == null)
30 {
31 string curUrl = context.Request.Url.ToString();
32
33 string currUser = "";
34 // 使用者登入檢查代碼
35 // .
36
37 if(currUser == null || currUser.Trim().Length == 0)
38 throw new Exception("你還不是本系統的使用者,如果需要進行本系統的操作,請聯絡管理員");
39 else
40 context.Session["Session_User"] = currUser;
41 }
42 }
43 catch (Exception ex)
44 {
45 throw ex;
46 }
47 }
48
49 public void Init(HttpApplication context)
50 {
51 context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
52 }
53
54 public void Dispose()
55 {
56
57 }
58 }
59}
60
然後再在 Web.Config 中增加如下設定。
<configuration>
<system.web>
<httpModules>
<add name="LoginModule" type="WebApplication1.LoginModule, WebApplication1" />
</httpModules>
</system.web>
</configuration>
這樣就把登入認證的操作統一在LoadModule中進行處理啦。省掉好多工作量