Introduction

If an application requires login, it also needs to know the current user performing operations. While ASP.NET itself provides Session objects in the presentation layer, ASP.NET Boilerplate provides IAbpSession interface to obtain current user and tenant wherever needed.

About IAbpSession

IAbpSession interface must be implemented in order to get actual session informations. While you can implement it in your own way, it's fully implemented in module-zero project.

IAbpSession is also fully integrated and used by other structures in ASP.NET Boilerplate (setting system and authorization system for instance).

Injecting session

IAbpSession is generally property injected to needed classes unless it's not possible to work without session informations. If we use property injection, we can use NullAbpSession.Instance as default value as shown below:

public class MyClass : ITransientDependency
{
    public IAbpSession AbpSession { get; set; }

    public MyClass()
    {
        AbpSession = NullAbpSession.Instance;
    }

    public void MyMethod()
    {
        var currentUserId = AbpSession.UserId;
        //...
    }
}

Since authorization is a application layer task, it's adviced to use IAbpSession in application layer and upper layers (we don't use it in domain layer normally). ApplicationService, AbpController and AbpApiController base classes has AbpSession already injected. So, you can directly use AbpSession property in an application service method for instance.

Using session properties

AbpSession defines a few key properties:

UserId and TenantId is nullable. There is also non-nullable GetUserId() and GetTenantId() methods. If you're sure there is a current user, you can call GetUserId(). If current user is null, this method throws exception. GetTenantId() is also similar.

Impersonator properties are not common as other properties and generally used for audit logging purposes.