Session统一处理

 在web系统中页面验证是不可少的,在页面比较多的系统中Session统一用户验证是必须的。

 httphander 与httpmodule 输出区别

    httphander 是有返回响应的,会重写输出结果  

    httpmodule 无响应结果输出,不会影响页面输出

   下面是利用HttpModule的Session统一验证

 

public class PageBase : IHttpModule
{
    public void Dispose() { }
    public void Init(HttpApplication context)
    {

        //实现事件

        context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
    }
    void context_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;

        //aspx 页面跳转地址
         string URL = System.Configuration.ConfigurationManager.AppSettings["DefaultURL"].ToString();
        //aspx 页面验证 

         if (app.Context.Request.Url.AbsoluteUri.Contains(".aspx"))
        {
            if (app.Context.Session["UserID"] == null)
            {
               //aspx 终止页面请求
               //这里很重要,因为HttpModule对页面输出没有影响,所以必须停止页面请求,不然的话页面照常输出

app.CompleteRequest();
//JS页面跳转 app.Context.Response.Write("<script>window.open('','_self','');window.close();window.open('" + URL + "');</script>"); } } //因为用的ajax.dll,所以当前session丢失时阻止其ajax操作 else if (app.Context.Request.Url.AbsoluteUri.Contains(".ashx?_method=")) { if (app.Context.Session["UserID"] == null) {
//这里很重要,因为HttpModule对页面输出没有影响,所以必须停止页面请求,不然的话页面照常输出



app.CompleteRequest(); app.Context.Response.Write(
"window.top.location.href ='Error.aspx';"); } } } }

    下面是利用HttpHander来统一验证Session 

//用HttpHander来控制页面Session验证
namespace WebHttpTest
{
    //在Httphander中使用Session必须继承IRequiresSessionState,IReadOnlySessionState接口
    public class HttpHander : IHttpHandler, IRequiresSessionState,IReadOnlySessionState
    {
        #region IHttpHandler メンバ

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            //获取请求页面
            string filePath = context.Server.MapPath(context.Request.FilePath);
            //Session跳转页面
            string errorFilePath = context.Server.MapPath("/Error.aspx");
            //判断Session
            if (context.Session["UserID"] == null)
            {
                //Session 跳转
                context.Response.TransmitFile(errorFilePath);
            }
            else 
            {
                //这句很重要,如果Session不为空正常跳转,
                //因为HttpHander 会重写页面输出,如果不写会输出空页面
                context.Response.TransmitFile(filePath);
            }
        }

        #endregion
    }
}

Web.config配置

 <httpHandlers >
      <add path="*" verb="*" type="WebHttpTest.HttpHander,WebHttpTest" />
    </httpHandlers>

 

 

posted @ 2013-11-04 09:59  巴顿道儿  阅读(439)  评论(0编辑  收藏  举报