如何根据cookie值

时间:2017-08-14 10:10:35

标签: c# cookies dependency-injection asp.net-core .net-core

我使用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

1 个答案:

答案 0 :(得分:1)

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

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

并且不使用var sp = services.BuildServiceProvider()

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

考虑检查您的设计。