0

I have this code

public UserProfile spUserProfileGet()
        {
            // this line throw : Object reference not set to an instance 
            var user = HttpContext.Current.User.Identity.Name;

            //...

        }

In my IIS Development setting, I have

Anonymous Authentication : Disabled
Windows Authentication : Enabled

And i am getting

Object reference not set to an instance 

Why is that ? I am using this class in many projects before with no problem :/

The HttpContext.Current.User is NULL, but why ?

Muflix
  • 6,192
  • 17
  • 77
  • 153
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – DavidG Sep 29 '16 at 09:01
  • yes, the User object is NULL, but why ? – Muflix Sep 29 '16 at 09:04
  • Read the duplicate question, it tells you exactly how to figure that out. – DavidG Sep 29 '16 at 09:06
  • 1
    @DavidG in this case generic advice on debugging null references is unlikely to help. If `User` is null it points to an issue with auth configuration. – Ant P Sep 29 '16 at 09:07
  • Maybe, the cause is that I use it in `Application_BeginRequest()` method and there is no user object yet, I will inspect this – Muflix Sep 29 '16 at 09:09

1 Answers1

0

The problem was, that I called HttpContext.Current.User from global.asax Application_BeginRequest() which does not contain this object yet. Here is description of application lifecycle https://msdn.microsoft.com/en-us/library/ms178473.aspx and when I copy the code to the Application_PostAuthenticateRequest, It works now.

The problem that remains, is that Application_PostAuthenticateRequest is triggered twice.

Muflix
  • 6,192
  • 17
  • 77
  • 153