1

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;
    }
9
  • 3
    Which line is throwing the exception? And why are you bothering with an if statement when the two paths do the same thing? Commented Jan 11, 2013 at 7:04
  • maybe HttpContext, Current or Session is null at runtime? ;-) Commented Jan 11, 2013 at 7:05
  • 2
    if and else part have the same statement Session.Clear()! ! Commented Jan 11, 2013 at 7:08
  • @Jon i edited the code ..but it is still giving the same error. Commented Jan 11, 2013 at 7:09
  • 1
    possible duplicate of What is a NullReferenceException in .NET? Commented Jan 11, 2013 at 7:11

3 Answers 3

2

As long as you have System.Web referenced in your using statements, then you should be able to use this:

if (Session != null) {Session.Clear();}

Or

if (Session != null) {Session.Abandon();}

Im not sure why you would you return a string which holds an integer though. A boolean value would make more sense, but you really shouldn't need anything in this context.

Also, your exception handler is attempting to catch a sqlexception, which could also be a source of an object reference error, as you don't appear to have any SQL objects in this function.

I'd probably do this following:

protected bool MemberLogOut()
{
    try {
        if (Session != null) {Session.Abandon();}
        //do any logging and additional cleanup here
        return true;
    } catch {
        return false;
    }
}

Edit: if you are in fact calling from outside of your web project, you can just pass the current httpcontext to the following method:

protected bool MemberLogOut(HttpContext context)
{
    try {
        if (context != null && context.Session != null) {
            context.Session.Abandon();
        }
        //do any logging and additional cleanup here
        return true;
    } catch (Exception ex) {
        //log here if necessary
        return false;
    }
}     
Sign up to request clarification or add additional context in comments.

7 Comments

-, Session is a property of eg System.Web.UI.Page-instance and can be accessed via a System.Web.HttpContext-instance for cases, where you don't have access to a page, control, ... therefore you'll need to use System.Web.HttpContext.Current, which can be null if you run that outside of a web-scenario! So... which Session-property are you referring to? another thing: if an exception occurs, you should log this one with a generic exception-handler catch (Exception ex)
-, still wrong ... context.Current.Session != null can throw an exception, as context.Current can be null ...
I get that. But in terms of what a responsive asp.net exceptions ping here... Do I even care to log exception that there was no session, when we're trying to close session in the first place. The deed is done.
you are partially correct: It's not best practice to use exceptions for control flows. Actually you are doing this by provoking an exception in case context.Current is null - it would be way better if you do another null-check, because this is a known behaviour (something exceptions should not be used for). another thing (and the reason why I still give a downvote on this answer): you are handling in a System.Web.HttpContext-instance, which does not have a Current-property, rather the caller does the method call with eg MemberLogOut(HttpContenxt.Current)
Yes, so with session being direct property of httpcontext, this code should work. Doing this off the top of my head on iPad due to the insomnia. Bad code makes me sleepy.
|
1

Can any one help me with what is wrong with my code

I guess that you are running this code outside an ASP.NET application. HttpContext.Current exists 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 HttpContext from 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.

5 Comments

Or... there is no Session.
@Darin Dimitrov Yes the code is in a class library and is being used across different applications..Can you please elaborate "you will have to remove the dependency on the HttpContext from it"..
Sure, I will elaborate. The correct way to handle this scenario is to define and use an abstraction for this Session object so that your method is weakly coupled from any ASP.NET specific objects. Then this method will take as argument your abstraction. You could define an interface such as ISession for example containing the required operations. Then you could have an implementation of this interface for a web application (which of course will simply wrap the actual HttpSessionState) and have another implementation when you want to use this library in other types of applications.
@DarinDimitrov For completeness and us lower mammals, can you add such an example to this answer? I want to use Session in another class, and it would be nice to know how. Microsoft has to just have public static void SetDataToSession<T>(this HttpSessionStateBase session, string key, object value) { .. } and it turns out to be bull because session is null, so doing session[key] = value throws a NullReferenceException. code.msdn.microsoft.com/How-to-create-and-access-447ada98
Actually, I did it for another answer I ran across after doing some more research into this: stackoverflow.com/questions/10629882/…
-1

try that code

public string MemberLogOut()
{
    string ret = string.Empty;
    try
    {
        if (HttpContext.Current.Session!=null)
        {HttpContext.Current.Session.Clear();}

    }
    catch (SqlException ex)
    {
        throw new Exception(ex.Message);
    }
    return "1";
}

6 Comments

-, HttpContext.Current could be null at first-hand.
@AndreasNiedermair So if HttpContext.Current is null, what could be the possible reason?
@dotnet_noob running the code in a console/service/wpf/winforms/...-application
@AndreasNiedermair Hi. i have checked and found out that HttpContext.Current is not null but HttpContext.Current.Session is null. I have two solutions, one contains the website and the other contains class libraries. The code that i have given is contained inside one of the class libraries. Can you explain why HttpContext.Current.Session is getting null values
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.