I have application page, hosted on Sharepoint server (for ex. http://myportal/mysite/_layouts/application/default.aspx), which has code like this:
protected void Page_PreLoad(object sender, EventArgs e)
{
var userEmail = SPContext.Current.Web.CurrentUser.Email;
}
If user tries to get this page directly by URL after browser starts, exception appears, because CurrentUser is null. But if user firstly navigates to web site (http://myportal/mysite) and then to application page, CurrentUser is not null. So, how can I get CurrentUser object if it is not initialized in SPContext?
Well... better late than never. I ran into this same problem today. The previous comment does not address the original poster's expressed problem. The problems comes when you publish .ASPX pages in the _Layouts folder, and then, when using Forms or Claims auth, make that custom page your first hit in a session (with no previously remembered login). SharePoint authentication isn't fired by default (even if you inherit from the LayoutsPageBase class). If you navigate to some other SharePoint page (such as _Layouts/15/Settings.aspx) and then come back, then the CurrentUser is filled in. I had to use Reflector to get a better clue of what was going on, and how to fix it. The short answer is, once you realize that the CurrentUser == null, you need to add this line of code:
In my case, this code generates a challenge/response to the browser, which I used to log in, and immediately following this line of code, the CurrentUser object is filled in correctly. Here is what my entire function ended up looking like: