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?
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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:
And the MSDN walkthrough of the application lifecycle:
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.
No, you must use
Application_AuthenticateRequest instead. That’s the earliest point where you have an user.