我正在尝试设置我的依赖注入,我需要从ASP.NET身份注入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<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);
}
}
答案 0 :(得分:11)
我用以下内容解决了这个问题:
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