IRequiresSessionState接口控制

时间:2023-03-09 09:55:16
IRequiresSessionState接口控制
  刚刚接触.net web端的朋友都会被Session坑过,莫名其妙的不能读取Session数据,后来知道原来有IRequiresSessionState这个接口,不继承的就不能读取Session里面的数据,知道这个以后呢,也不清楚里面具体是如何实现的。对此一直不甘心,于是查了各方面的资料终于模拟出来了。
  在一般处理程序(ashx文件)里面有个一个(HttpContext Context),F12进入HttpContext 类你面你会发现它应该是用了单例的模式,里面有个 public static HttpContext Current { get; set; },应该是确定程序只有一个上下文。接下来可以找到public HttpSessionState Session { get; },这就是我们需要读取Session。
废话少说,首先说明用到了反射。我们来介绍下Type 类中的Type IsAssignableFrom(Type c);方法。假设A类继承了B接口,  Type a = typeof(A);  Type b = typeof(B); 那么 a. IsAssignableFrom(b)的值为ture;这个可以判断类是否继承了IRequiresSessionState。这是第一步。
  第二步就是找到当前访问Session的类。这个就要用到StackTrace类,从名字上来看这个类是用来跟踪代码的。这里面要用到StackTrace 的GetFrame(index)方法和GetMethod(); 。GetFrame(index)这个是从调用的最里层往外层遍历,它的返回值也是StackTrace 。是GetMethod() 返回值是MethodBase,而MethodBase的ReflectedType属性可以得到当前类的Type。
  原理都在上面的,下面的代码是模拟过程。
  
using System;
using System.Diagnostics;
using System.Reflection;
using System.Web.SessionState; namespace Ztest
{
public class Program: IRequiresSessionState
{
public static void Main(string[] args)
{
try
{
if (Test.Current.session == null)
{
Console.WriteLine("没有继承IRequiresSessionState");
}
else
{
Console.WriteLine(Test.Current.session);
}
}
catch (Exception ex)
{
}
Console.ReadLine();
}
}
public class Test
{
private Test()
{
Type basetype = typeof(IRequiresSessionState);
StackTrace trace = new StackTrace();
int i = 0;
Type type;
while (true)
{
///找到外层第一个调用类
MethodBase methodName = trace.GetFrame(i).GetMethod();
type = methodName.ReflectedType;
if (type != typeof(Test))
{
break;
}
i++;
} Boolean key = basetype.IsAssignableFrom(type);
if (key)
{
session = _m;
}
else
{
session = null;
}
}
private static Test _Current;
private string _m = "当前类实现了IRequiresSessionState";
/// <summary>
/// 模拟session
/// </summary>
public Object session { get; set; }
public static Test Current
{
get
{
return get();
}
set
{
Current = value;
}
}
private static Test get()
{
if (_Current == null)
{
_Current = new Test(); }
return _Current;
}
} }