【发布时间】:2017-03-07 03:18:57
【问题描述】:
我目前正在更新使用 MembershipProvider 和 RoleProvider 的旧 ASP.NET Webforms 应用程序,以使用较新的 ASP.NET Identity 类。此外,我使用 Autofac 进行依赖注入,并且为了保持一致性,我希望能够将它与新的 Identity 类一起使用。
ASP.NET Identity 现在依赖于 OWIN 中间件,通过添加以下 Startup.cs 类,我已经成功地将 OWIN 中间件设置合并到我的应用程序中:
internal partial class Startup
{
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
AutofacConfig.RegisterTypes(builder);
AutofacConfig.RegisterIdentityTypes(builder, app);
var container = builder.Build();
Global.SetContainer(container);
app.UseAutofacMiddleware(container);
ConfigureAuth(app);
}
}
我像这样使用 Autofac 注册身份类:
internal static class AutofacConfig
{
public static void RegisterIdentityTypes(ContainerBuilder builder, IAppBuilder app)
{
builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();
}
}
当我导航到我的 WebForms 登录页面时,我可以看到以下 ApplicationSignInManager 类被实例化,并且它的构造函数参数也被解析,这表明 Autofac 工作正常。
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(
ApplicationUserManager userManager,
IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
// userManager is valid
// authenticationManager is valid
}
}
当我单击 WebForms 登录页面上的登录按钮时,将调用以下方法,并通过 Autofac 属性注入实例化 ApplicationSignInManager。然后调用正确的 Identity 类实现。
public partial class SignIn : BasePage
{
// Autofac property injection
public ApplicationSignInManager ApplicationSignInManager { get; set; }
....
protected void SignInClick(object sender, EventArgs e)
{
// Validate the user password
var result = this.ApplicationSignInManager.PasswordSignIn(
this.email.Text,
this.password.Text,
this.remember.Checked,
true);
....
}
所以一切似乎都很好,但我觉得有些不对劲,我看不到 OWIN 和 Autofac 的连接位置,甚至不需要。如果我从 Startup.cs 中删除以下行...
app.UseAutofacMiddleware(container);
...一切仍然正常运行!哪一个不对,不是吗?
许多 MVC 示例似乎表明这是获取 Identity 对象的正确方法(通过 GetOwinContext() 调用):
protected void SignInClick(object sender, EventArgs e)
{
var signInManager = this.Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
// Validate the user password
var result = signInManager.PasswordSignIn(
this.email.Text,
this.password.Text,
this.remember.Checked,
true);
....
}
但在执行该代码时,“signInManager”变量始终为 NULL。
我真的需要这行代码吗?
app.UseAutofacMiddleware(container);
谁能指出我正确的方向?
【问题讨论】:
标签: c# webforms owin autofac asp.net-identity-2