C# 为什么 HttpContext.Current.Session["value"].ToString() 在 App_Code 类文件中给出空值,对象引用未设置为对象的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11984992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why HttpContext.Current.Session["value"].ToString() gives null value inside App_Code class file, Object reference not set to an instance of an object
提问by Satinder singh
Here Scenario is HttpContext.Current.Session["value"].ToString() gives null value, even have already set session value when user login.
这里的场景是 HttpContext.Current.Session["value"].ToString() 给出空值,甚至在用户登录时已经设置了会话值。
My webconfig
我的网络配置
<sessionState timeout="40" mode="InProc"/>
My global.asax
我的 global.asax
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["EmployeeId"] = "";
this.Session["DomainName"] = "";
}
In my Defaultpage.asppx.cs
在我的 Defaultpage.aspx.cs
Emp_grade empgrd = new Emp_grade();gives Object reference not set to an instance of an object
Emp_grade empgrd = new Emp_grade();给出未设置为对象实例的对象引用
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Configuration;
public partial class EmpGrade : System.Web.UI.Page
{
//here am getting error(The type initializer for 'Emp_grade' threw an exception)
// stack error message Object reference not set to an instance of an object.
Emp_grade empgrd = new Emp_grade();
protected void Page_Load(object sender, EventArgs e)
{
logic code...
Datatable dt= empgrd.EmpRecord();
}
}
In my App_Code folderi have class file Emp_grade.cs
在我的App_Code folder我有类文件Emp_grade.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Web.SessionState;
public class Emp_grade
{
public Emp_grade()
{
//TODO: Add constructor logic here
}
static string getConnection = HttpContext.Current.Session["DomainName"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[getConnection].ConnectionString);
public DataTable EmpRecord()
{
logic code
}
}
My login page:
我的登录页面:
protected void Page_Load(object sender, EventArgs e)
{
//set some value
Session["DomainName"] = domainname;
}
ScreenShot(Debugging)
截图(调试)
采纳答案by user1429080
You should probably refactor a bit. This:
您可能应该重构一下。这个:
static string getConnection = HttpContext.Current.Session["DomainName"].ToString();
is a static field with an initializer. It will run once, and keep whatever value it got until the application is restarted. And it will run at a time that is not very well defined, it is only guranteed that it will run sometime before it is first accessed.
是带有初始化程序的静态字段。它将运行一次,并保留它获得的任何值,直到应用程序重新启动。并且它会在一个不是很好定义的时间运行,只保证它会在第一次访问之前的某个时间运行。
This means that it may well run at a time when no HttpContextis present (like Dan Puzeywrote) which will cause an exception to be thrown. Any subsequent attempt to access it will (to the best of my knowledge) result in the same Exception being thrown.
这意味着它很可能在 noHttpContext存在的时候运行(就像Dan Puzey写的那样),这将导致抛出异常。任何后续尝试访问它都会(据我所知)导致抛出相同的异常。
But keep in mind that it is only fetched once, so even if the initializer were to succeed and find a value, that value will be used for all subsequent uses of getConnection. It will not be fetched anew for each different user.
但请记住,它仅被提取一次,因此即使初始化程序成功并找到一个值,该值也将用于getConnection. 不会为每个不同的用户重新获取它。
To fix that, you could wrap it in an instance method:
为了解决这个问题,你可以将它包装在一个实例方法中:
private string GetDomainName()
{
return HttpContext.Current.Session["DomainName"].ToString();
}
SqlConnection conn = null;
and then initialize connin the constructor:
然后conn在构造函数中初始化:
public Emp_grade()
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings[GetDomainName()].ConnectionString);
}
Please also note the since this class is initializing and storing a SqlConnection(which is IDisposable), your class should also implement the IDisposableinterface. For background information about implementing IDisposable, see for instance this answer.
另请注意,由于此类正在初始化和存储 a SqlConnection(即IDisposable),因此您的类还应实现该IDisposable接口。有关实施的背景信息IDisposable,请参阅例如此答案。
EDIT: The screenshot shows that the HttpContext.Current.Sessionis returning null.
编辑:屏幕截图显示HttpContext.Current.Session正在返回空值。
The reason is this line:
原因是这一行:
Emp_grade empgrd = new Emp_grade();
This is declaring an instance member in the Page class, with an initializer. The initializer is run very early in the request pipeline, so at the point when it runs the Session is not yet present in the context.
这是在 Page 类中声明一个实例成员,带有一个初始化程序。初始化程序在请求管道中很早运行,因此在它运行时,上下文中尚不存在 Session。
Change to:
改成:
Emp_grade empgrd = null;
protected void Page_Load(object sender, EventArgs e)
{
empgrd = new Emp_grade();
Datatable dt = empgrd.EmpRecord();
}
回答by Dan Puzey
You're referencing .Session["DomainName"]in a constructor for a static field. That will potentially run before any of your other code does. Quite possibly it will run outside of any HttpContextat all, because chances are it'll run as the application initialised, before the first request is processed.
您在.Session["DomainName"]静态字段的构造函数中引用。这可能会在您的任何其他代码之前运行。很可能它会在任何之外运行HttpContext,因为它可能会在应用程序初始化时运行,在第一个请求被处理之前。
I suspect that making getConnectionnon-static will fix the problem.
我怀疑制作getConnection非静态会解决这个问题。

