日期:2014-05-16  浏览次数:20774 次

asp.net中一般处理程序获取session

asp.net的一般处理程序 .ashx的context对象默认是取不出session的值出来的

要达到取出Session的效果,则需要让它实现System.Web.SessionState.IReadOnlySessionState接口(该接口没有任何方法实现,只是起到一个标识作用)


为了让所有的一般处理程序都能获取到Session值,并且能集中做一些控制管理(比如用户认证、权限控制等),我的策略是让一个抽象类实现IHttpHandler, IRequiresSessionState接口,然后让其他所有一般处理程序都继承该抽象类即可。


Demo:

抽象类

using System;
using System.Web;
using System.Web.SessionState;
....

namespace SRERC.Web.admin
{
    /// <summary>
    /// SessionAwareHandler 的摘要说明
    /// </summary>
    public abstract class SessionAwareHandler : IHttpHandler, IRequiresSessionState
    {
         
         .....

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            
            // 身份认证
            
            // 权限控制

            MyProcess(context);

        }

       ........


      protected abstract void MyProcess(HttpContext context);

     }
}

一般处理程序实现类:

using System;
using System.Web;

namespace SRERC.Web.admin
{
    /// <summary>
    /// bandHandler 的摘要说明
    /// </summary>
    public class bandHandler : SessionAwareHandler
    {
        protected override void MyProcess(HttpContext context)
        {
             //....处理过程
	     //....
             context.Response.Write(json);
  
        }

    }
}

ok,也算是解决了问题吧

也不知道还有没有更好的方案