asp.net-corerazor-pages

ASP.NET Core custom page model not able to access ClaimsPrincipal.User in Razor page


I am new to ASP.Net Core and have a custom PageModel (MTNCBasePageModel) that inherits from the PageModel abstract class.

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApp.SharedKernal
{
    public class MTNCBasePageModel : PageModel
    {

        public bool IsAuthenticated = false;
        public bool IsEditor = false;
        public bool IsAdmin = false;
 
        public MTNCBasePageModel() : base()
        {
            IsAuthenticated = User.Identity.IsAuthenticated;
        }
    }
}

When the MTNCBasePageModel constructor is called the User is null.

What am I missing here?


Solution

  • You cannot access the User object directly from the constructor. Because the User object, which represents the current HTTP context's user information, is set up later in the request lifecycle, after the constructor is executed.

    The recommended approach to access the User object is to do so in the request handling methods like OnGet, OnPost, etc.

    For example:

    public void OnGet()
    {
        // You can access the User object here
        IsAuthenticated = User.Identity.IsAuthenticated;
    }