Where Session ?
来源:互联网 发布:工业设计用到的软件 编辑:程序博客网 时间:2024/05/12 08:21
说起来,真的是惭愧,一直以为Session不能用在自定义的CS类中(aspx的后台CS文件之外的类文件),我之所以是这么想,是因为在自定义类文件中,直接输入Session,编译器没有智能感应;再者,我请教了某个"高手",高手说"怎么可能,CS类文件没有经过asp.net HttpModule管线,系统没有加载会话状态,所以自定义的类文件中,决不能使用Session",细细想来,觉得也没什么不妥当的地方,于是便默认了他的这种观点(你是不是也还这样想呢?).
于是,我经常埋怨Asp.net之父ScottGu,埋怨他为什么要这样设计?如果我要在中间件类库中使用会话状态,却不能使用,启不是很痛苦?(我埋怨他很长一段时间,其实我错了,他没有错,sorry)
仔细想想,发现我的思路,似乎被那"高手"引导到了一条错误的路线上,cs文件似乎与asp.net HttpModule管线没什么关系.因为,只要http请求的资源符合asp.net筛选器,asp.net runtime就会在http管线中,经过HttpMoudule的某个点,请求生成会话状态,所以,可以推断,会话状态对象与类文件无关.
实验一,在App_Data内部类文件中,使用会话状态
public class TestClass
{
public TestClass()
{
}
public void GetSession()
{
HttpContext.Current.ApplicationInstance.Session["name"] = "王孟军";
}
}
{
public TestClass()
{
}
public void GetSession()
{
HttpContext.Current.ApplicationInstance.Session["name"] = "王孟军";
}
}
实验二,在网站外的类库中,使用会话状态
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace TessClassLib
{
public class Class1
{
public void GetSessionLib()
{
HttpContext.Current.ApplicationInstance.Session["otherName"] = "郭孟军";
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace TessClassLib
{
public class Class1
{
public void GetSessionLib()
{
HttpContext.Current.ApplicationInstance.Session["otherName"] = "郭孟军";
}
}
}
页面类文件调用情况
protected void Button1_Click(object sender, EventArgs e)
{
TestClass ts = new TestClass();
ts.GetSession();
Class1 c = new Class1();
c.GetSessionLib();
Response.Write(Session["name"].ToString() + "---" + Session["otherName"].ToString() );
}
{
TestClass ts = new TestClass();
ts.GetSession();
Class1 c = new Class1();
c.GetSessionLib();
Response.Write(Session["name"].ToString() + "---" + Session["otherName"].ToString() );
}
效果
很明显,我的想法是正确的,在内部类和外边类都可以使用会话状态,只不过获取她的方式不同而已.
使用Session需要注意的几个地方
有朋友喜欢自己实现IhttpModule,以便在运行时,能做一些控制,其实只有在context.AcquireRequestState事件的委托方法中,或者她后面的委托方法中才能使用会话状态,如果在他之前调用Session,自然会抛出nullException.
如果要在自己定义IhttpHandler中使用会话状态,务必要实现IRequiresSessionState接口.
总结
虽然这个话题,对某些高手而言,只不过是一雕虫小技耳,但还是希望对那些困惑的朋友,有所启发,有所帮助(代码实在简单,就不提供下载了)
- Where Session ?
- 使用ThreadLocal来存储Session,以便实现Session any where
- where
- @Where
- where
- where
- where
- where()
- Where Case
- WHERE 子句
- C# where
- WHERE.....OR(........)
- where in
- Where子句
- Where子句
- Where子句
- where.bat
- where sql
- 取得屏幕上任意点的象素值
- 使用 Oracle XmlDom 包创建xml文件例程
- 空数组的使用 - 很有用
- 关于Perl里面正则规范
- Oracle调优
- Where Session ?
- 使用 Spring 2 Portlet MVC 框架构建 Portlet 应用
- C的memcpy,memmove和strcpy的区别是什么?
- 算法之二叉查找树
- 基于分页内存的 HASH MAP
- vc6中集成驱动编译环境的配置方法
- Node Based ShaderGenerator Features list
- 视频教程:Zoomla!逐浪CMS使用教程之模板与风格开发
- JAVA如何调用DOS命令