Describes how to use the Session function in the ABP framework and the session function in the abp framework.

Source: Internet
Author: User

Describes how to use the Session function in the ABP framework and the session function in the abp framework.

If an application needs to log on, it must know what operations the current user has performed. Therefore, ASP. NET provides a set of SESSION objects on the presentation layer, while ABP provides a set of SESSION objects that can be used anywhere.
Obtain the IAbpSession interface of the current user and tenant.

IAbpSession
To obtain session information, you must implement the IAbpSession interface. Although you can implement it (IAbpSession) in your own way, it has been fully implemented in the module-zero project.

Inject Session
An IAbpSession is usually contained in the class that requires it in the form of property injection. It is not required for classes that do not need to obtain session information. If we use the property injection method, we can use
NullAbpSession. Instance is used as the default value to initialize it (IAbpSession), as shown below:

public class MyClass : ITransientDependency{  public IAbpSession AbpSession { get; set; }  public MyClass()  {    AbpSession = NullAbpSession.Instance;  }  public void MyMethod()  {    var currentUserId = AbpSession.UserId;    //...  }}

Because authorization is a task at the application layer, we should use IAbpSession on the application layer and the application layer (it is normal that we do not use IAbpSession on the domain layer ).
The basic classes ApplicationService, AbpController, and AbpApiController have been injected with the AbpSession attribute. Therefore, you can directly use the AbpSession attribute in the Application Service instance method.

Use Session attributes
Some key attributes defined by AbpSession:

  • UserId: ID of the current user. If the current user does not exist, it is null. If you need to authorize access, it cannot be blank.
  • TenantId: ID of the current tenant. If no current tenant exists, it is null.
  • MultiTenancySide: It may be Host or Tenant.

UserId and TenantId can be null. Of course, the GetUserId () and GetTenantId () methods for getting data when it is not null are also provided. If you are sure you have the current user, you can use the GetUserId () method.

If the current user is empty, an exception is thrown. The usage of GetTenantId () is similar to that of GetUserId.

How to Implement Session
Directory code:

Class diagram:

IAbpSession: IAbpSession Interface

using Abp.MultiTenancy;namespace Abp.Runtime.Session{  public interface IAbpSession  {    long? UserId { get; }    int? TenantId { get; }    MultiTenancySides MultiTenancySide { get; }    long? ImpersonatorUserId { get; }    int? ImpersonatorTenantId { get; }  }}

NullAbpSession: implements the Null Object Mode.

using Abp.MultiTenancy;namespace Abp.Runtime.Session{  /// <summary>  /// Implements null object pattern for <see cref="IAbpSession"/>.  /// </summary>  public class NullAbpSession : IAbpSession  {    /// <summary>    /// Singleton instance.    /// </summary>    public static NullAbpSession Instance { get { return SingletonInstance; } }    private static readonly NullAbpSession SingletonInstance = new NullAbpSession();    /// <inheritdoc/>    public long? UserId { get { return null; } }    /// <inheritdoc/>    public int? TenantId { get { return null; } }    public MultiTenancySides MultiTenancySide { get { return MultiTenancySides.Tenant; } }        public long? ImpersonatorUserId { get { return null; } }        public int? ImpersonatorTenantId { get { return null; } }    private NullAbpSession()    {    }  }}

ClaimsAbpSession: obtains the session status.

using System;using System.Linq;using System.Security.Claims;using System.Threading;using Abp.Configuration.Startup;using Abp.MultiTenancy;using Abp.Runtime.Security;namespace Abp.Runtime.Session{  /// <summary>  /// Implements <see cref="IAbpSession"/> to get session properties from claims of <see cref="Thread.CurrentPrincipal"/>.  /// </summary>  public class ClaimsAbpSession : IAbpSession  {    private const int DefaultTenantId = 1;    public virtual long? UserId    {      get      {        var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;        if (claimsPrincipal == null)        {          return null;        }        var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity;        if (claimsIdentity == null)        {          return null;        }        var userIdClaim = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);        if (userIdClaim == null || string.IsNullOrEmpty(userIdClaim.Value))        {          return null;        }        long userId;        if (!long.TryParse(userIdClaim.Value, out userId))        {          return null;        }        return userId;      }    }    public virtual int? TenantId    {      get      {        if (!_multiTenancy.IsEnabled)        {          return DefaultTenantId;        }        var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;        if (claimsPrincipal == null)        {          return null;        }        var tenantIdClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.TenantId);        if (tenantIdClaim == null || string.IsNullOrEmpty(tenantIdClaim.Value))        {          return null;        }        return Convert.ToInt32(tenantIdClaim.Value);      }    }    public virtual MultiTenancySides MultiTenancySide    {      get      {        return _multiTenancy.IsEnabled && !TenantId.HasValue          ? MultiTenancySides.Host          : MultiTenancySides.Tenant;      }    }    public virtual long? ImpersonatorUserId    {      get      {        var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;        if (claimsPrincipal == null)        {          return null;        }        var impersonatorUserIdClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.ImpersonatorUserId);        if (impersonatorUserIdClaim == null || string.IsNullOrEmpty(impersonatorUserIdClaim.Value))        {          return null;        }        return Convert.ToInt64(impersonatorUserIdClaim.Value);      }    }    public virtual int? ImpersonatorTenantId    {      get      {        if (!_multiTenancy.IsEnabled)        {          return DefaultTenantId;        }        var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;        if (claimsPrincipal == null)        {          return null;        }        var impersonatorTenantIdClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.ImpersonatorTenantId);        if (impersonatorTenantIdClaim == null || string.IsNullOrEmpty(impersonatorTenantIdClaim.Value))        {          return null;        }        return Convert.ToInt32(impersonatorTenantIdClaim.Value);      }    }    private readonly IMultiTenancyConfig _multiTenancy;    /// <summary>    /// Constructor.    /// </summary>    public ClaimsAbpSession(IMultiTenancyConfig multiTenancy)    {      _multiTenancy = multiTenancy;    }  }}

AbpSessionExtensions: IAbpSession Extension Method

using System;namespace Abp.Runtime.Session{  /// <summary>  /// Extension methods for <see cref="IAbpSession"/>.  /// </summary>  public static class AbpSessionExtensions  {    /// <summary>    /// Gets current User's Id.    /// Throws <see cref="AbpException"/> if <see cref="IAbpSession.UserId"/> is null.    /// </summary>    /// <param name="session">Session object.</param>    /// <returns>Current User's Id.</returns>    public static long GetUserId(this IAbpSession session)    {      if (!session.UserId.HasValue)      {        throw new AbpException("Session.UserId is null! Probably, user is not logged in.");      }      return session.UserId.Value;    }    /// <summary>    /// Gets current Tenant's Id.    /// Throws <see cref="AbpException"/> if <see cref="IAbpSession.TenantId"/> is null.    /// </summary>    /// <param name="session">Session object.</param>    /// <returns>Current Tenant's Id.</returns>    /// <exception cref="AbpException"></exception>    public static int GetTenantId(this IAbpSession session)    {      if (!session.TenantId.HasValue)      {        throw new AbpException("Session.TenantId is null! Possible problems: No user logged in or current logged in user in a host user (TenantId is always null for host users).");      }      return session.TenantId.Value;    }    /// <summary>    /// Creates <see cref="UserIdentifier"/> from given session.    /// Returns null if <see cref="IAbpSession.UserId"/> is null.    /// </summary>    /// <param name="session">The session.</param>    public static UserIdentifier ToUserIdentifier(this IAbpSession session)    {      return session.UserId == null        ? null        : new UserIdentifier(session.TenantId, session.GetUserId());    }  }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.