我试图通过注入一个Ninject UserFactory,这里是我的绑定:Ninject总是注入空HttpContext.Current()
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项目,如果这对方法有什么不同。
更新: 我也曾尝试下面的代码不错误,但我注入CurrentUserProvider
财产保持为空:
kernel.Bind<ICurrentUserProvider>().To<CurrentUserProvider>().InRequestScope()
.WithConstructorArgument("context", ninjectContext => HttpContext.Current);
嗯,首先,你真的不应该再解密AUTH的cookie像这样,你也不应该使用会话来存储用户ID信息。您应该改为使用自定义的IPrincipal,例如此处定义的:http://peterbromberg.net/post/Implementing-a-Custom-IPrincipal-in-an-ASPNET-MVC-Application.aspx – 2015-03-14 01:53:40
感谢您的提醒,我会研究一下。在这种情况下,我不使用会员资格,而是使用定制身份验证cookie的定制身份验证。该cookie仅存储非敏感数据。 – Simon 2015-03-14 20:37:57
会员与任何事情有什么关系? IPrincipal是与FormsAuthentication相关的,而不是与会员相关的。这个例子使用成员资格,但你可以使用任何你想要的。 – 2015-03-15 03:18:06