如何从Global.asax获取OwinContext

本文关键字:获取 OwinContext asax Global | 更新日期: 2023-09-27 18:12:07

我正试图设置我的依赖注入,我需要从ASP注入IAuthenticationManager。. NET标识到OwinContext .

这是我从我的Global.asax -> ServiceConfig.Configure()运行:

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

但是当我运行我的应用程序时,我得到这个消息:

没有owin。在上下文

中找到环境项。

为什么HttpContext.Current.GetOwinContext()在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);
    }
}

如何从Global.asax获取OwinContext

我用下面的方法修复了这个问题:

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

似乎OwnContext在启动时不存在,所以我将等待它并在它存在时注入它。请注意,container.IsVerifying()出现在SimpleInjector.Advanced