16-HttpModule

ASP.NET請求處理過程是基于管道模型的,這個管道模型是由多個HttpModule和HttpHandler組成,當請求到達

HttpModule的時候,系統還沒有對這個請求真正處理,但是我們可以在這個請求傳遞到處理中(HttpHandler)

之前附加一些其它信息,或者截獲的這個請求并做一些額外的工作 。

本教程主要使用httpModule判斷是否登錄以及角色權限:

(1)未登錄用戶不能訪問Admin文件夾下所有文件(跳轉到登錄頁面)。

(2)登錄用戶,角色為super可以訪問Admin下所有文件。

(3)登錄用戶,角色為common只能訪問Admin下Book以及Order文件夾下資源,不能訪問SysManage文件夾

下資源。如果訪問SysManage文件夾下資源,跳轉到Admin下的Index,后臺管理首頁。

一、資料準備

本示例程序沒有用到數據庫,使用一個泛型集合保存系統用戶信息。

網站目錄結構如下:

0014.PNG

實體類如下:

public class UserEntity
{
    public UserEntity()
    {
        ;
    }
    public UserEntity(string account, string pwd, string role)
    {
        this.Account = account;
        this.Pwd = pwd;
        this.Role = role;
    }

    public string Account { get; set; } //用戶名
    public string Pwd { get; set; } //密碼
    public string Role { get; set; } //角色(super-超級管理員,common-普通管理員)
}

二、編寫HttpModule

創建一個UserLoginModule.cs文件,代碼如下:

//必須實現Init和Dispose方法
public class UserLoginModule:IHttpModule
{
    public UserLoginModule()
    {
        //
        //TODO: 在此處添加構造函數邏輯
        //
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }

    public void Init(HttpApplication context)
    {
        //throw new NotImplementedException();
        //context.PreRequestHandlerExecute += Context_PreRequestHandlerExecute;
        context.AcquireRequestState += Context_PreRequestHandlerExecute;
    }

    private void Context_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = application.Context;
        Uri url = context.Request.Url;

        if (url.AbsolutePath.ToLower().Contains("/admin"))
        {
            if (context.Session != null && context.Session["User"] == null)
            {
                context.Response.Redirect("~/Login.aspx?myurl=" + url.AbsolutePath);
            }
        }
        if (url.AbsolutePath.ToLower().Contains("/sysmanage"))
        {
            UserEntity User = new UserEntity();
            User = (UserEntity)context.Session["User"];
            if (User.Role.Equals("super") == false)
            {
                context.Response.Redirect("~/Admin/Index.aspx");
            }
        }
    }
}

三、配置文件配置

根目錄下的web.config如下:

<?xml version="1.0"?>
<!--
  有關如何配置 ASP.NET 應用程序的詳細信息,請訪問
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
    <!--IIS6配置-->
        <httpModules>
            <add name="LoginModule" type="UserLoginModule"/>
        </httpModules>
    
    </system.web>
  
  <!--IIS7配置-->
  <!--<system.webServer>
    <modules>
      <add name="LoginModule" type="UserLoginModule"/>
    </modules>
  </system.webServer>-->
  
</configuration>

四、用戶登錄

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>登錄</h1>
        <p>
            賬號:<asp:TextBox ID="txtAccount" runat="server"></asp:TextBox>
        </p>
        <p>
            密碼:<asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox>
        </p>
        <p>
            <asp:Button ID="btnLogin" runat="server" Text="登錄" onclick="btnLogin_Click"/>
            <asp:Label ID="lblInfo" runat="server" Text="" ForeColor="Red"></asp:Label>
        </p>
    </div>
    </form>
</body>
</html>
public partial class Login : System.Web.UI.Page
{
    public List<UserEntity> listUser = new List<UserEntity>();
    protected void Page_Load(object sender, EventArgs e)
    {
        listUser.Add(new UserEntity("admin", "admin", "super"));
        listUser.Add(new UserEntity("liudehua", "123456", "common"));
        listUser.Add(new UserEntity("zhoujielun", "123456", "common"));
    }

    #region 登錄
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        List<UserEntity> listTemp = new List<UserEntity>();
        listTemp = listUser.Where(p => p.Account.Equals(this.txtAccount.Text) && p.Pwd.Equals(this.txtPwd.Text)).ToList();
        if (listTemp.Count != 1)
        {
            this.lblInfo.Text = "用戶名或密碼錯誤!";
            return;
        }
        else
        {
            Session["User"] = listTemp[0];
            if (Request["myurl"] == null || Request["myurl"].Equals(""))
                Response.Redirect("~/Admin/Index.aspx");
            else
                Response.Redirect(Request["myurl"]);
        }
    }
    #endregion
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容