如何从Global.asax中获取OwinContext?
如何从Global.asax中获取OwinContext?
我正在尝试设置我的依赖注入,并且我需要将ASP.NET Identity的IAuthenticationManager注入到OwinContext中。
为此,在我的Global.asax的ServiceConfig.Configure()方法中执行以下操作:
container.Register(() => HttpContext.Current.GetOwinContext().Authentication);
但是当我运行应用程序时,我收到以下消息:
没有在上下文中找到owin.Environment项。
为什么Global.asax中的HttpContext.Current.GetOwinContext()不可用?
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
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获取OwinContext的问题。他们试图在应用程序启动时获取OwinContext,但是发现它并不存在。他们使用了SimpleInjector框架,通过以下代码解决了这个问题:
container.RegisterPerWebRequest(() => { if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null && container.IsVerifying()) { return new OwinContext().Authentication; } return HttpContext.Current.GetOwinContext().Authentication; });
在这段代码中,他们使用了container.RegisterPerWebRequest()方法来注册OwinContext。这个方法是SimpleInjector.Advanced命名空间中的一个扩展方法。
另外,有人提出了在Castle Windsor中如何实现同样的功能的问题。他们给出了以下解决方法:
container.Register(Component.For().UsingFactoryMethod( () => { if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null) { return new OwinContext().Authentication; } return HttpContext.Current.GetOwinContext().Authentication; }).LifestylePerWebRequest());
以上就是从Global.asax中获取OwinContext的问题的原因和解决方法。通过这些代码,我们可以在应用程序启动时获取OwinContext并注入到需要它的组件中。