如何从Global.asax获取OwinContext? [英] How to get OwinContext from Global.asax?
问题描述
我正在尝试设置我的依赖项注入,并且需要从ASP.NET身份向OwinContext
注入IAuthenticationManager
.
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
.
为此,我来自我的Global.asax -> ServiceConfig.Configure()
跑步:
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:
在上下文中未找到owin.Environment项目
No owin.Environment item was found in the context
为什么无法从Global.asax获得此HttpContext.Current.GetOwinContext()?
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);
}
}
推荐答案
我使用以下方法解决了这个问题:
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;
});
似乎OwnContext在启动时不存在,因此我将等待它并在存在后将其注入.请注意,container.IsVerifying()
存在于SimpleInjector.Advanced
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
这篇关于如何从Global.asax获取OwinContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!