views:

214

answers:

2

I'm trying to get a reference to the user object in my Global.asax file's Application_BeginRequest. I'm using the property Context.User but I get a NullReferenceException. Is it possible to get a user object reference in Application_BeginRequest?

+5  A: 

No, you must use Application_AuthenticateRequest instead. That's the earliest point where you have an user.

Julien Lebosquain
This throws an exception, still no user or what?Sub Application_AuthenticateRequest() If Context.User Is Nothing Then Throw New Exception("No user")End Sub
Ropstah
+6  A: 

You don't have access to the User object because the request hasn't yet been authenticated.

Try using Application_AuthenticateRequest instead.

Here is an explanation of all Global.asax events: http://articles.techrepublic.com.com/5100-10878_11-5771721.html

And the MSDN walkthrough of the application lifecycle: http://msdn.microsoft.com/en-us/library/ms178473.aspx

Edit: I see what you're doing. Change your if statement to and if not statement (sorry if syntax is wrong, I don't use VB.NET):

 Sub Application_AuthenticateRequest() 
   If Context.User <> Nothing Then 
      Throw New Exception("User now exists") 
 End Sub 

You'll notice that this method gets hit more than once. The exception won't be thrown until the second or third time. That is because every request follows the application lifecycle. So, instead of performing whatever action when the user is null, you should perform it when the user is not null.

If your goal is to restrict access dynamically, you should create a separate HttpModule and assign it to the files you're restricting

However, you'll need to be careful not to undertake rewriting the entire ASP.NET Application Security infrastructure. You can, instead, restrict access to certain folders based on role.

Jim Schubert
great articles.
Chris Lively
Please check my comment in the other answer by Julien... http://stackoverflow.com/questions/3072768/net-application-beginrequest-how-to-get-user-reference/3072801#3072801
Ropstah
ropstah: I see now what is happening. The application is making multiple requests (maybe for images, scripts, stylesheets, etc.) before the authentication request is processed. Those other file requests may not need authentication and that is why your exception is being thrown. Try the update in my answer and see if that clarifies. Also, what are you trying to achieve with your code that requires the User object?
Jim Schubert
This was not the case, however it **was** related to the `Global.asax` lifecycle. I needed the `User.IsInRole()` functionality which was only available **after** _Application_AuthenticateRequest_ namely in the procedure `Application_AuthorizeRequest()`
Ropstah
Thanks, ropstah. I'm glad I could set you on the right path to debugging the problem.
Jim Schubert