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,也算是解決了問題吧
也不知道還有沒有更好的方案