Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

asp.net - c# how to set up and use session state from preinit

OK so to set and read variables from the current session

String Myvar =(string) System.Web.HttpContext.Current.Session[“MyVariable”]

To set

System.Web.HttpContext.Current.Session[“MyVariable”] = “NewValue”

I can do neither, I get a System.NullReferenceException: Object reference not set to an instance of an object. from System.Web.HttpContext.Current.Session.

In my web.config I have

<sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" cookieless="false" timeout="20">
</sessionState>  

I have read a dozen articles on the the necessity of IHttpHandler and an IRequiresSessionState interface. I think the issue may be caused because I am requesting this information in Page_PreInit. I found a solution in a stack overflow article but I don't seem be using it properly to actually make this go.

I am not sure what I am missing. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the comment mentioned, is there some reason you need this in the PreInit event?

PreInit happens very early in the page lifecycle. It happens, in fact, before even the master page (if any) is applied, before all the controls are fully initialized, etc.

A much better choice for the majority of applications is in the Load event. If you're still getting a NullReferenceException there, then there's a bigger issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...