C#中无法检查会话是否存在? [英] C# Cannot check Session exists?
问题描述
我得到一个错误,当我做到以下几点:
如果(会话[值]!= NULL)
{
// code
}
我的错误是这样的:
对象引用未设置到对象的实例。
这是为什么?我总是检查我会这样?我使用的MVC框架,这样做有什么关系呢?
编辑:
在code是在控制器的构造函数:
公共类myController的:ControllerBase
{
私人诠释无功; 公共myController的()
{
如果(会话[值]!= NULL)
{
MVAR =(INT)会议[值];
}
}
}
会议期间的处理的行动只是真的存在 - 我不希望它成为一个构造函数有效控制器。例如,控制器可能(据我所知)被请求之间重复使用。
您将需要做到这一点无论是在动作(方法),或(或许更恰当)的动作过滤器,或 OnActionExecuting
(ETC)的方法(S ):
公共抽象类ControllerBase:控制器
{
保护覆盖无效OnActionExecuting(
ActionExecutingContext filterContext)
{
// code涉及this.Session //编辑简化
base.OnActionExecuting(filterContext);在编辑//重新添加
}
}
I get an error when I do the following:
if(Session["value"] != null)
{
// code
}
The error i get is this:
Object reference not set to an instance of an object.
Why is this? I always check my session this way? I am using the MVC Framework, does this has something to do with it?
EDIT:
The code is in the constructor of a Controller:
public class MyController : ControllerBase
{
private int mVar;
public MyController()
{
if (Session["value"] != null)
{
mVar= (int)Session["value"];
}
}
}
The session only really exists during the processing of an action - I wouldn't expect it to be valid in the constructor of a controller. For example, the controller might (for all I know) be re-used between requests.
You will need to do this either in the action (method), or (perhaps more appropriately) in an action filter, or the OnActionExecuting
(etc) method(s):
public abstract class ControllerBase : Controller
{
protected override void OnActionExecuting(
ActionExecutingContext filterContext)
{
// code involving this.Session // edited to simplify
base.OnActionExecuting(filterContext); // re-added in edit
}
}
这篇关于C#中无法检查会话是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!