gpt4 book ai didi

c# - 如何从 Global.asax 获取 OwinContext?

转载 作者:可可西里 更新时间:2023-11-01 03:10:26 24 4
gpt4 key购买 nike

我正在尝试设置我的依赖注入(inject),我需要将 IAuthenticationManager 从 ASP.NET Identity 注入(inject)到 OwinContext

为此,我从我的 Global.asax -> ServiceConfig.Configure() 运行:

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

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

No owin.Environment item was found in the context

为什么这个 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);
}
}

最佳答案

我用以下方法解决了这个问题:

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

});

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

关于c# - 如何从 Global.asax 获取 OwinContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24660380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com