In the below code i got an error “Object reference not set to an instance of an object” in the line of the ‘if’ condition. Can any one help me with what is wrong with my code.
public string MemberLogOut()
{
string ret = string.Empty;
try
{
if (HttpContext.Current.Session.Count > 0)
HttpContext.Current.Session.Clear();
ret="1";
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
ret="2";
}
return ret;
}
I guess that you are running this code outside an ASP.NET application.
HttpContext.Currentexists only inside the context of a web application. If you ever attempt to run this code outside (for example in a console, desktop, unit test, …) it’s never gonna work.So if this is some sort of code that is in a class library intended to be reused across different applications you will have to remove the dependency on the
HttpContextfrom it.Side remark: your if condition seems kinda useless as you are doing exactly the same thing in the else as well as in the if -> clearing the session.