How to get OwinContext from Global.asax?

蓝咒 提交于 2020-01-01 04:07:28

问题


I am trying to set up my Dependency Injection and I am in the need of injecting a IAuthenticationManager from ASP.NET Identity to an OwinContext.

For this I am from my Global.asax -> ServiceConfig.Configure() running:

 container.Register(() => HttpContext.Current.GetOwinContext().Authentication);

But when I am running my application I get this message:

No owin.Environment item was found in the context

Why is this HttpContext.Current.GetOwinContext() not available from Global.asax?

Startup.cs

[assembly: OwinStartupAttribute(typeof(MyApp.Web.Startup))]
namespace Speedop.Web
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

Startup.Auth.cs

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager<User, int>, User, int>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie),
                    getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))
                    )
            }
        });

        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    }
}

回答1:


I fixed this with the following:

container.RegisterPerWebRequest(() =>
{
    if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null && container.IsVerifying())
    {
        return new OwinContext().Authentication;
    }
    return HttpContext.Current.GetOwinContext().Authentication;

});

Seems like the OwnContext is not present at startup, so I'll wait for it and inject it once its present. Please note that the container.IsVerifying() is present in SimpleInjector.Advanced



来源:https://stackoverflow.com/questions/24660380/how-to-get-owincontext-from-global-asax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!