C#实现接口IHttpModule完成统一的权限验证

测试代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Web;
using Test.Model;

namespace TestPermission
{
    class PermissionHttpModule : System.Web.IHttpModule
    {
        public void Init(HttpApplication httpApplication)
        {
            httpApplication.AcquireRequestState += (new EventHandler(this.Application_AcquireRequestState));
        }

        private void Application_AcquireRequestState(Object source, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)source;
            string url = httpApplication.Context.Request.Path.ToLower();

            if (url.IndexOf("/admin/") > -1 
                && httpApplication.Context.Session != null 
                && httpApplication.Context.Session["Cache:Role"] != null)
            {
                IList list = (IList)httpApplication.Context.Session["Cache:Role"];
                if (url.IndexOf("admin/users/") > -1 && !CheckPermission(list, "用户管理"))
                {
                    ShowPagePermissionError(httpApplication);
                }
            }
        }

        public void Dispose()
        {

        }

        /// <summary>
        /// 是否有该模块的权限
        /// </summary>
        /// <param name="list"></param>
        /// <param name="PermissionName"></param>
        /// <returns></returns>
        private bool CheckPermission(IList list, string PermissionName)
        {
            bool retBool = false;
            PermissionModel model;
            for (int i = 0; i < list.Count; i++)
            {
                model = (PermissionModel)list[i];
                if (model.parentName == PermissionName)
                {
                    retBool = true;
                    break;
                }
            }
            return retBool;
        }

        /// <summary>
        /// 跳转到权限错误页
        /// </summary>
        /// <param name="Application"></param>
        private void ShowPagePermissionError(HttpApplication Application)
        {
            Application.Context.Response.Redirect("../PermissionError.htm", true);
        }

    }
}

例子中是按栏目来验证的,比如“用户管理”。

如果功能权限信息全面的话,同样可以做功能权限的验证。

当然,web.config中还要配置HttpModule,参考:

<configuration>
    <system.web>
       <httpModules>           
      <add name="PermissionHttpModule" type="TestPermission.PermissionHttpModule,TestPermission"/>
    </httpModules> </system.web> </configuration>

MSDN资料:http://msdn.microsoft.com/zh-cn/library/vstudio/system.web.ihttpmodule(v=vs.80).aspx 

 

posted @ 2013-11-14 17:07  志在必得Shaun  阅读(1552)  评论(0编辑  收藏  举报