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

标签 c# asp.net-mvc asp.net-mvc-4 ninject

<分区>

我正在尝试通过 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);

最佳答案

感谢 NightOwl888 用 this answer 为我指明了正确的方向.

我没有尝试使用 Ninject 直接使用 HttpContext,而是按照以下方式注入(inject)了一个工厂对象:

  public class AspNetUserContext : IUserContext
{
    public User CurrentUser
    {
        // Do not inject HttpContext in the ctor, but use it
        // here in this property
        get { return new User(HttpContext.Current.User); }
    }
}

关于c# - Ninject 总是注入(inject) null HttpContext.Current(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29038402/

相关文章:

.net - 在哪里可以找到 "stable"或 "release"版本的 MVC Mini Profiler 源代码?

ASP.NET MVC 模型绑定(bind)器无法使用字典

asp.net - 使用HttpRequestMessage.Properties承载每个请求的上下文

asp.net-mvc - 如何使 Web API 操作只能从我的应用程序访问?

c# - MVC 模型验证多 View

javascript - GetElementById 返回未定义的值

c# - 预检失败时如何通过属性而不是通过 Application_BeginRequest 启用 CORS

c# - Cookie 身份验证和 Asp Net Core 2.0 迁移

c# - Windows 窗体将 List 传递给新窗体

c# - Visual Studio 2015 中缺少 sqlite 的 ADO.NET 数据源