我有一个 MVC 5 项目,该项目已被修改为使用 int 作为标识的主键,如本指南所示
然后,我按照本指南中所述启用了电子邮件确认
一切都如预期的那样顺利。然后我安装了 structuremap.mvc5 用于依赖注入,并添加了修改后的 DefaultRegistry.cs
public DefaultRegistry() {
Scan(
scan => {
scan.TheCallingAssembly();
scan.WithDefaultConventions();
scan.AssemblyContainingType(typeof(MyProject.Data.MyDbContext));
scan.With(new ControllerConvention());
});
//For<IExample>().Use<Example>();
For<IUserStore<ApplicationUser, int>>().Use<MyUserStore>().LifecycleIs<HttpContextLifecycle>();
For<IAuthenticationManager>().Use(() => HttpContext.Current.GetOwinContext().Authentication);
}
项目构建良好,但当尝试在站点上注册新用户时,发送电子邮件确认现在会引发异常 System.NotSupportedException:调用UserManager时未注册IUserTokenProvider。GenerateEmailConfirmationTokenAsync(userID)。
private async Task<string> SendEmailConfirmationTokenAsync(int userID, string subject)
{
string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
var callbackUrl = Url.Action("ConfirmEmail", "Account",
new { userId = userID, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(userID, subject,
"Please confirm your account by clicking <a href="" + callbackUrl + "">here</a>");
return callbackUrl;
}
我是依赖注入的新手,很确定我做错了什么。我将感谢您的想法和见解。
,IUserTokenProvider
由 OWIN 插入,但是当您从 DI 容器解析UserManager
时,提供IUserTokenProvider
的组件不可用,并且此组件未初始化。
可用时将令牌提供程序分配给全局静态变量,然后在构造函数UserManager
重用它:
public class AuthConfig
{
public static IDataProtectionProvider DataProtectionProvider { get; set; }
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
DataProtectionProvider = app.GetDataProtectionProvider();
// do other configuration
}
}
然后在用户管理器构造函数的构造函数中重新分配它:
public UserManager(/*your dependecies*/)
{
var dataProtectorProvider = AuthConfig.DataProtectionProvider;
var dataProtector = dataProtectorProvider.Create("My Asp.Net Identity");
this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, Guid>(dataProtector)
{
TokenLifespan = TimeSpan.FromHours(24),
};
// other stuff
}