步步为营-81-HttpModule(再谈Session)

说明:session用于记录数据信息并存放在服务器内存中,但是存在一些问题.例如当使用服务器集群是会出现session丢失等情况.虽然微软提供了一些解决方案(Session进程外存储,或者存到数据库中),但是效果不尽人意.常用的还是Memcache或者Redis等分布式缓存

步步为营-76-用户登录(Session+Cookie)的1.4中通过封装CheckSession来实现身份校验(在请求管道的第11和第12事件中间),其实还可以通过HttpModule来实现(请求管道的第9个事件,AcquireRequestState),

1.1 创建实现IHttpModule接口的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace NewsCommon
{
    //01 定义SessionHttpModule,实现IHttpModule接口
    public class SessionHttpModule:IHttpModule
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
           
            context.AcquireRequestState += context_AcquireRequestState;
        }

       public void context_AcquireRequestState(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
           //获取当前的httpcontext
            HttpContext context = application.Context;
           //获取用户请求的URL地址
            string url = context.Request.Url.ToString();
            if (url.Contains("后台页面"))
            {
                if (context.Session["userInfo"] == null)
                {
                    context.Response.Redirect("/Login.aspx");
                }
            }
        }
    }
}
SessionHttpModule

1.2 配置WebConfig文件

  <!--配置HttpModule -->
  <system.webServer>
    <modules>
      <add name="SessionHttpModule" type="NewsCommon.SessionHttpModule"/>
    </modules>
  </system.webServer>
webconfig

posted @ 2017-06-20 16:37  逍遥小天狼  阅读(312)  评论(0编辑  收藏  举报