另外值得注意的是,在非Web项目中使用HttpContext.Current.Cache、HttpContext.Current.Session等的时候,最好进行判断HttpContext.Current是否为空:
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
string test = HttpContext.Current.Session["Session"].ToString();
}
这是因为有些情况下Session或者Cache等会被截断,比如在.ashx文件中,默认情况下就会截断Session。当然也可以通过设置在.ashx文件中使用Session,但是为了安全,最后进行判断。
如果要在.ashx文件中使用Session,那么要先引用“using System.Web.SessionState;”,然后继承接口“IRequiresSessionState”,下面是一个例子:
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.SessionState;
namespace Lemon.Life.WebData
{
///
/// 演示“在.ashx中使用Session”
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Xml : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Session["Test"] = "Test";
string test = context.Session["Test"].ToString();
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{ return false;}
}
}
}
没有评论:
发表评论