C# 如何基于cookie值将用户对象从启动类注入控制器构造函数
我使用CookieAuthentication实现自定义登录C# 如何基于cookie值将用户对象从启动类注入控制器构造函数,c#,cookies,dependency-injection,asp.net-core,.net-core,C#,Cookies,Dependency Injection,Asp.net Core,.net Core,我使用CookieAuthentication实现自定义登录 app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = "MyCookieMiddlewareInstance", LoginPath = new PathString("/Account/Unauthorized/"), AccessDeniedPath = new PathString("/
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new PathString("/Account/Unauthorized/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieName="Id",
});
我的应用程序中的每个控制器都需要一个用户对象,该对象可以使用cookie中的机密id(CookieName=“id”
)创建。
如何通过读取cookie并在每次请求时注入控制器来创建用户对象
我尝试了以下方法
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
var sp = services.BuildServiceProvider();
services.AddTransient<IUserContext, UserObject>(a => new UserObjectResolver(sp.GetService<IHttpContextAccessor>()).GetUserObject());
}
public void配置服务(IServiceCollection服务)
{
services.AddSingleton();
var sp=services.BuildServiceProvider();
AddTransient(a=>newUserObjectResolver(sp.GetService()).GetUserObject());
}
但是在这里,请求到达时,
IHttpContextAccessor
似乎总是null
。实现工厂函数采用IServiceProvider
参数,因此您需要更新到
services.AddTransient<IUserContext>(provider =>
new UserObjectResolver(provider.GetService<IHttpContextAccessor>()).GetUserObject()
);
services.AddTransient(提供者=>
新的UserObjectResolver(provider.GetService()).GetUserObject()
);
不要使用
var sp=services.BuildServiceProvider()
我还建议创建一个过滤器来检查cookie,并创建用户的IPrincipal
。至少到那时,请求已经有时间进行初始化,默认情况下,所有控制器都可以访问该主体
考虑查看您的设计。
ConfigureServices
在服务启动时运行,此时没有用户上下文;没有发出HTTP请求。你不能做你想做的事,并且期望它能起作用。重新思考你的方法。代码片段中的sp
来自哪里?这是一个输入错误吗?var sp=services.BuildServiceProvider(),更新了代码段。我建议将UserObjectResolver注入控制器,并使用构造函数依赖项作为其对IHttpContextAccessor的依赖项,而不是将其更新。然后使用它让用户进入控制器,而不是尝试注入user@Psb我建议创建一个过滤器来检查cookie并创建用户的主体。至少到那时,请求已经有时间进行初始化,默认情况下,所有控制器都可以访问该主体。正如我之前所说,请检查您的设计。