WEB頁面統一認證登入方法

來源:互聯網
上載者:User

在每一個頁面的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中進行處理啦。省掉好多工作量

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.