gpt4 book ai didi

c# - Ninject 总是注入(inject) null HttpContext.Current()

转载 作者:太空宇宙 更新时间:2023-11-03 13:10:21 26 4
gpt4 key购买 nike

<分区>

我正在尝试通过 Ninject 注入(inject)一个 UserFactory,这是我的绑定(bind):

  var u = new CurrentUserProvider(HttpContext.Current);
kernel.Bind<ICurrentUserProvider>().ToMethod(context => u).InRequestScope();

此工厂使用 HttpContext 读取身份验证 cookie 并填充 CurrentUser 对象,HttpContext 作为构造函数参数传递:

 public class CurrentUserProvider : ICurrentUserProvider
{
public ICurrentUser CurrentUser { get; set; }

public CurrentUserProvider(HttpContext context)
{
CurrentUser = GetCurrentUser(context);
}

private static ICurrentUser GetCurrentUser(HttpContext ctx)
{
var httpCookie = ctx.Request.Cookies[".ASPXAUTH"];

if (httpCookie != null)
{
var cookie = httpCookie.Value;
var ticket = FormsAuthentication.Decrypt(cookie);

if (ticket != null)
{
var x = ticket.UserData.FromJson<CurrentUser>();
ctx.Session["UserID"] = x.DatabaseName;
return x;
}
}
return null;
}
}

然而,传递给 UserFactory 构造函数的 HttpContext 始终为 null。如果这对方法有任何影响,那么这是一个 MVC4 项目。

更新:我还尝试了以下没有错误的代码,但我注入(inject)的 CurrentUserProvider 属性仍然为空:

 kernel.Bind<ICurrentUserProvider>().To<CurrentUserProvider>().InRequestScope()
.WithConstructorArgument("context", ninjectContext => HttpContext.Current);

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