加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何根据cookie值将用户对象从启动类注入到控制器构造函数

发布时间:2020-12-15 22:46:41 所属栏目:百科 来源:网络整理
导读:我正在使用CookieAuthentication来实现自定义登录, app.UseCookieAuthentication(new CookieAuthenticationOptions(){ AuthenticationScheme = "MyCookieMiddlewareInstance",LoginPath = new PathString("/Account/Unauthorized/"),AccessDeniedPath = new
我正在使用CookieAuthentication来实现自定义登录,

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());
}

但是在这里,IHttpContextAccessor似乎在请求到达时始终为null.

解决方法

实现工厂函数采用IServiceProvider参数,因此您需要更新到

services.AddTransient<IUserContext>(provider => 
    new UserObjectResolver(provider.GetService<IHttpContextAccessor>??()).GetUserObject()
)??;

而不是使用var sp = services.BuildServiceProvider()

我还建议创建一个过滤器,它将检查cookie并创建用户的IPrincipal.至少在那时,请求已经有时间被初始化,并且所有控制器默认都可以访问该主体.

考虑检查您的设计.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读