21
5

在类库项目(或者其他非Web项目中)有时候需要HttpContext.Current这个方法,我们发现在类里面添加了引用“using System.Web;”之后还是不行,其实解解这个问题很简单,只需要在该项目的“引用”中添加System.Web这个引用就可以了。
另外值得注意的是,在非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;}
}
}
}

公告栏

欢迎大家来到我的博客,我是dodoro,希望我的博客能给你带来帮助。