0

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;
    }
Niar
  • 512
  • 1
  • 10
  • 23
  • 3
    Which line is throwing the exception? And why are you bothering with an `if` statement when the two paths do the same thing? – Jon Skeet Jan 11 '13 at 07:04
  • maybe HttpContext, Current or Session is null at runtime? ;-) – rhe1980 Jan 11 '13 at 07:05
  • 2
    `if` and `else` part have the same statement `Session.Clear()`! ! – V4Vendetta Jan 11 '13 at 07:08
  • @Jon i edited the code ..but it is still giving the same error. – Niar Jan 11 '13 at 07:09
  • 1
    possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) –  Jan 11 '13 at 07:11
  • @AndreasNiedermair i have already read that question..i was not able to find any solution from it..so i created this question. – Niar Jan 11 '13 at 07:14
  • @dotnet_noob you then did neither understoodnd the answers nor the issue ... quote from the **first answer**: _NullReferenceException always means the same thing. You are trying to use a reference to an object, but you haven't initialized it (or it used to be initialized, but is now uninitialized)._ not that hard ... –  Jan 11 '13 at 07:16
  • @AndreasNiedermair That's kind of obvious - but that doesn't tell us why Session has to be initialized or how to do so. Don't be simplistic - that doesn't answer the question fully. – vapcguy Oct 30 '18 at 20:53
  • Related - https://stackoverflow.com/questions/10629882/asp-net-mvc-session-is-null/53073664#53073664 – vapcguy Oct 30 '18 at 22:19

3 Answers3

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;
    }
}     
Dperish
  • 36
  • 3
  • 1
    -, `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)` –  Jan 11 '13 at 08:03
  • 1
    -, still wrong ... `context.Current.Session != null` can throw an exception, as `context.Current` can be null ... –  Jan 11 '13 at 08:06
  • 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. – Dperish Jan 11 '13 at 08:10
  • 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)` –  Jan 11 '13 at 08:14
  • 2
    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. – Dperish Jan 11 '13 at 08:20
  • Still can't really see the need for logging an exception at this point in an application, or why it would need a return value at all. – Dperish Jan 11 '13 at 08:21
  • ... me neither. But if the OP needs states, (s)he can also go for an enum. Logging might me useful at the development-stage, eg you mock an http-request - but that's a bit contrived, I must admit :) –  Jan 11 '13 at 08:26
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.

Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
  • 1
    Or... there is no Session. – Steven Jan 11 '13 at 07:07
  • @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".. – Niar Jan 11 '13 at 07:18
  • 1
    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. – Darin Dimitrov Jan 11 '13 at 07:30
  • @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(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`. https://code.msdn.microsoft.com/How-to-create-and-access-447ada98 – vapcguy Oct 30 '18 at 20:57
  • Actually, I did it for another answer I ran across after doing some more research into this: https://stackoverflow.com/questions/10629882/asp-net-mvc-session-is-null/53073664#53073664 – vapcguy Oct 30 '18 at 22:20
-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";
}
Frank59
  • 2,783
  • 2
  • 29
  • 44
  • 1
    -, `HttpContext.Current` could be null at first-hand. –  Jan 11 '13 at 07:12
  • @AndreasNiedermair So if HttpContext.Current is null, what could be the possible reason? – Niar Jan 11 '13 at 07:25
  • 2
    @dotnet_noob running the code in a console/service/wpf/winforms/...-application –  Jan 11 '13 at 07:26
  • @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 – Niar Jan 11 '13 at 08:49
  • 1
    @dotnet_noob http://stackoverflow.com/questions/1382791/asp-net-what-to-do-if-current-session-is-null –  Jan 11 '13 at 09:28
  • @AndreasNiedermair i was just checking this other link http://stackoverflow.com/questions/11984992/why-httpcontext-current-sessionvalue-tostring-gives-null-value-inside-app any way thanks.i will try to find my way from here. – Niar Jan 11 '13 at 09:30