As I start integrating ASP.NET Core Web with the business layer of DasBlog I came across some code that started throwing null reference exceptions because CurrentPrincipal was null:

     filter += EntryCollectionFilter.DefaultFilters.IsPublic();

If you have happened to have a passing familiarity with authentication and authorization you have inevitably come across IPrincipal (or IClaimsPrinciple), which are designed to communicate the identity and role of the current principle. So in traditional Web Forms application deep in the bowels of HttpApplication a principal is set on the thread executing your web page. The problem with the above business layer code is that it is making assumptions about how the UI layer is updating the principal.

So what has changed? I am not using HttpApplication because this is not Web Forms, also by design ASP.NET Core Web has removed the public static member variable CurrentPrincipal, which is inline with our contemporary ideas of unit testing and dependency injection.

Great! So how do you get access to Principle in ASP.NET Core Web?

All your defined controllers indirectly inherit from ControllerBase and it in turn has the User member variable which is a ClaimsPrinciple type (inherits IPrinciple). So from any of your controllers you gain direct access to claims of the current principle with User.

If you need to access the Principle from locations other than your controller you can access HttpContextAccess via dependency injection (again the User member variable is IPrinciple). The following code goes in the ConfigureServices method of the Startup class.

services.AddTransient( provider => 

The world of software development has a real fascination with dependency injection and I for one applaud this change.

Comment Section

Comments are closed.