Reputation: 21999
I have a Session that stores an int. I usually do the following...
if(Session["test"] == null)
Now that I am comparing...
public ActionResult NumbersGame(int myNum)
{
if(Session["test"] != myNum)...
How do I do that?
Upvotes: 0
Views: 13227
Reputation: 31862
Simple overview of how I would do it:
It may solve other problems too:
First we define interface:
public interface ISessionWrapper
{
int? SomeInteger { get; set; }
}
Then we make HttpContext implementation:
public class HttpContextSessionWrapper : ISessionWrapper
{
private T GetFromSession<T>(string key)
{
return (T) HttpContext.Current.Session[key];
}
private void SetInSession(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
public int? SomeInteger
{
get { return GetFromSession<int?>("SomeInteger"); }
set { SetInSession("SomeInteger", value); }
}
}
Then we define our base controller:
public class BaseController : Controller
{
public ISessionWrapper SessionWrapper { get; set; }
public BaseController()
{
SessionWrapper = new HttpContextSessionWrapper();
}
}
Finally:
public ActionResult NumbersGame(int myNum)
{
if (SessionWrapper.SomeInteger == myNum)
//Do what you want;
}
No need to cast here!! And if you wanted to test your controller, you have no problem with Session. You just Mock ISessionWrapper and pass it to SessionWrapper variable.
Upvotes: 1
Reputation: 1785
Another way of checking and using the value stored in your Session() object involves using the TryParse feature.
int intTest;
if (int.TryParse(Session["test"].ToString(), out intTest))
{
// intTest will have the value in Session["Test"] stored as an integer
}
I like it because it's compact and simple.
Upvotes: 1
Reputation: 124776
I would test for null (to detect Session expiry), then cast:
object value = Session["test"];
if (value == null)
{
// The value is not in Session (e.g. because the session has expired)
// Deal with this in an application-specific way, e.g. set to a default,
// reload the Session variable from the database, redirect to a home page, ...
...
}
else
{
myNumber = (int) value;
}
...
The problem with using Convert.ToInt32
is that it will simply return 0 if your session has expired, which may not be desirable depending on your application.
Upvotes: 0
Reputation: 5753
(int)Session["test"] will fail if that session variable is either null or not a number. Use this instead...
var myNumber = Convert.ToInt32(Session["test"]);
myNumber will be 0 if 'test' is null or not a number
Upvotes: 5