AbpSessionExtensions.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. namespace Abp.Runtime.Session
  2. {
  3. /// <summary>
  4. /// Extension methods for <see cref="IAbpSession"/>.
  5. /// </summary>
  6. public static class AbpSessionExtensions
  7. {
  8. /// <summary>
  9. /// Gets current User's Id.
  10. /// Throws <see cref="AbpException"/> if <see cref="IAbpSession.UserId"/> is null.
  11. /// </summary>
  12. /// <param name="session">Session object.</param>
  13. /// <returns>Current User's Id.</returns>
  14. public static long GetUserId(this IAbpSession session)
  15. {
  16. if (!session.UserId.HasValue)
  17. {
  18. throw new AbpException("Session.UserId is null! Probably, user is not logged in.");
  19. }
  20. return session.UserId.Value;
  21. }
  22. /// <summary>
  23. /// Gets current Tenant's Id.
  24. /// Throws <see cref="AbpException"/> if <see cref="IAbpSession.TenantId"/> is null.
  25. /// </summary>
  26. /// <param name="session">Session object.</param>
  27. /// <returns>Current Tenant's Id.</returns>
  28. /// <exception cref="AbpException"></exception>
  29. public static int GetTenantId(this IAbpSession session)
  30. {
  31. if (!session.TenantId.HasValue)
  32. {
  33. 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).");
  34. }
  35. return session.TenantId.Value;
  36. }
  37. /// <summary>
  38. /// Creates <see cref="UserIdentifier"/> from given session.
  39. /// Returns null if <see cref="IAbpSession.UserId"/> is null.
  40. /// </summary>
  41. /// <param name="session">The session.</param>
  42. public static UserIdentifier ToUserIdentifier(this IAbpSession session)
  43. {
  44. return session.UserId == null
  45. ? null
  46. : new UserIdentifier(session.TenantId, session.GetUserId());
  47. }
  48. }
  49. }