gpt4 book ai didi

c# - 有没有一种简单的方法可以让 ClassLibrary 获取 session 值?

转载 作者:太空宇宙 更新时间:2023-11-03 22:33:58 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用 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(); 以使依赖注入(inject)工作。

关于c# - 有没有一种简单的方法可以让 ClassLibrary 获取 session 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56035940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com