如何自动调用时,会话["东西&QUOT]的方法抛出一个NullReferenceException? [英] How to automatically call a method when Session["something"] throws a NullReferenceException?
问题描述
我要使用会话[firmaid]
很很多在我的应用程序。当有人登录到我的系统设置此值。
I am going to be using Session["firmaid"]
quite alot in my application. This value is set when someone logs in to my system.
如果有事情发生,并且这个值是从会话丢失了,我想以某种方式有一个全球性的方法,将得到它,如果它抛出一个的NullReferenceException
。
If something happens, and this value is lost from the Session, i would like to somehow have a global method that will get it, if it throws a NullReferenceException
.
我怎样才能做到这一点?
How can i do this?
目前,我的解决办法是尽量抓住每一个我使用时间会话[firmaid]
,然后执行,将放在firmaid在会话的方法,如果抛出一个例外
。
Currently, my solution is to try and catch every time i use Session["firmaid"]
, then execute the method that will put firmaid in the Session, if it throws an Exception
.
有没有更简单的方法来做到这一点?
Is there an easier way to do this?
推荐答案
相反的try /捕获每次你可以换一个强类型类访问会话,然后通过这个包装访问会话。
Instead of try/catching everytime you could wrap the access to the session in a strongly typed class and then access the session through this wrapper.
甚至写一个扩展方法:
public static class SessionExtensions
{
public static string GetFirmaId(this HttpSessionStateBase session)
{
var firmaid = session["firmaid"] as string;
if (string.IsNullOrEmpty(firmaid))
{
// TODO: call some method, take respective actions
}
return firmaid;
}
}
,然后在code,而不是:
and then in your code instead of:
try
{
var firmaid = Session["firmaid"];
// TODO: do something with the result
}
catch (Exception ex)
{
// TODO: call some method, take respective actions
}
使用:
var firmaid = Session.GetFirmaId();
// TODO: do something with the result
这篇关于如何自动调用时,会话["东西&QUOT]的方法抛出一个NullReferenceException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!