有没有一种简单的方法可以让 ClassLibrary 获取会话值?

Is there a way for a simple way for ClassLibrary to get Session Value?

我有一个外部 ClassLibrary 项目需要从主项目中的 HomeController 获取会话值集。 有没有简单的方法可以做到这一点?

或者是否有其他方法可以将值从 HomeController 传输到外部 ClassLibrary?

如果你使用Abp模板,Abp应用服务ApplicationService已经包含属性AbpSession,你可以继承这个class。

您可以使用 IHttpContextAccessor class

For other framework and custom components that require access to HttpContext, the recommended approach is to register a dependency using the built-in dependency injection container. The dependency injection container supplies the IHttpContextAccessor to any classes that declare it as a dependency in their constructors.

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc()
         .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     services.AddHttpContextAccessor();
     services.AddTransient<IUserRepository, UserRepository>(); 
}

In the following example:

  • UserRepository declares its dependency on IHttpContextAccessor.
  • The dependency is supplied when dependency injection resolves the dependency chain and creates an instance of UserRepository.

.

public class UserRepository : IUserRepository
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserRepository(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void LogCurrentUser()
    {
        var username = _httpContextAccessor.HttpContext.User.Identity.Name;
        service.LogAccessRequest(username);
    }
}

不要忘记添加 services.AddHttpContextAccessor(); 以使依赖注入工作。

single-responsibility 原则规定 class 应该只做一件事。虽然你可以注入像 IHttpContextAccessor 这样的东西,然后需要 class 了解像 HttpContextSession 这样的概念,但事实上它被用在网络环境中第一名等

正确的方法是注入或传递。如果 class 需要来自会话变量的特定值,请在您的控制器中访问该逻辑实际所属的会话,然后仅将会话中的值传递给您的外部 class.