c# - 生成密码重置 token 时出现身份 IUserEmailStore 错误

标签 c# asp.net webforms asp.net-identity

一些相关的问题: Webforms ASP.NET Identity system reset password

我正在尝试使用身份系统实现密码恢复,但遇到了错误(Store 未实现 IUserEmailStore)。这就是我正在做的,我正在使用 Visual Studio 2013 Web。使用 Web 窗体(正在学习 MVC),用户使用他们的电子邮件注册,并存储在数据库的用户名字段中。 我在 IdentityModel.cs 中添加了 UserManager 类:

public class UserManager : UserManager<ApplicationUser>
{

    public UserManager()
        : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
    {
        UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
        this.UserTokenProvider = new EmailTokenProvider<ApplicationUser, string>();
        this.EmailService = new EmailService();
    }

} 

public class EmailService : IIdentityMessageService
{
     public Task SendAsync(IdentityMessage message)
       {
        //email service here to send an email.
        return Task.FromResult(0);
       }
}

在 IdentityModels.cs 中,我还添加了助手:

public static string GetResetPasswordRedirectUrl(string code)
    {
        return "/Account/ResetPassword?" + CodeKey + "=" + HttpUtility.UrlEncode(code);
    }

这些是我在 IdentityModels.cs 类中所做的所有更改。现在,对于 ForgotPassword.aspx 页面,我已完成以下操作:

 protected void ResetPassword(object sender, EventArgs e)
    {
        if (IsValid)
        {
             var manager = new UserManager();
             var user = new ApplicationUser();
             user = manager.FindByName(Email.Text);                
            // Check if the the user does not exist                
            if (user == null)
            {
                ErrorText.Text = "User Could not be found.";
                return;
            }

            string token = manager.GeneratePasswordResetToken(user.Id);
            string callbackUrl = IdentityHelper.GetResetPasswordRedirectUrl(token);
            manager.SendEmail(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>.");
            Link.NavigateUrl = callbackUrl;
        }
    }

我的代码卡住了 string token = manager.GeneratePasswordResetToken(user.Id); 给出这个异常(exception)

{"Store does not implement IUserEmailStore<TUser>."}

关于异常的详细信息:

System.NotSupportedException was unhandled by user code
  HResult=-2146233067
  Message=Store does not implement IUserEmailStore<TUser>.
  Source=Microsoft.AspNet.Identity.Core
  StackTrace:
      at Microsoft.AspNet.Identity.UserManager`2.GetEmailStore()
      at Microsoft.AspNet.Identity.UserManager`2.<GetEmailAsync>d__a3.MoveNext()
   --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.AspNet.Identity.EmailTokenProvider`2.<GetUserModifierAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.AspNet.Identity.TotpSecurityStampBasedTokenProvider`2.<GenerateAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.AspNet.Identity.UserManager`2.<GenerateUserTokenAsync>d__e9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNet.Identity.UserManager`2.<GeneratePasswordResetTokenAsync>d__4f.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNet.Identity.AsyncHelper.RunSync[TResult](Func`1 func)
   at Microsoft.AspNet.Identity.UserManagerExtensions.GeneratePasswordResetToken[TUser,TKey](UserManager`2 manager, TKey userId)
   at uCk.Account.ForgotPassword.Forgot(Object sender, EventArgs e) in c:\Users\Tim\Documents\Visual Studio 2013\Projects\uCk\uCk\Account\ForgotPassword.aspx.cs:line 38
   at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

我从异常中了解到我应该实现 IUserEmailStore 接口(interface)?我不确定我应该在这里做什么;如果您看一下我添加的 Usermanager() 实现 EmailService() 难道还不够吗?我如何克服错误并达到预期的结果?

最佳答案

你的UserStore<>执行不执行IUserEmailStore<>所以你需要从 UserStore<> 派生以及实现IUserEmailStore<>像这样

public class UserStore : UserStore<ApplicationUser>, IUserEmailStore<ApplicationUser>
{
    public UserStore() : base(new ApplicationDbContext()){}

    public Task<TUser> FindByEmailAsync(string email)
    {
        //implement
    }

    //... implement other methods required etc
}

然后在您的经理构造函数中引用您的新商店

public class UserManager : UserManager<ApplicationUser>
{

    public UserManager() : base(new UserStore())
    {
        UserValidator = new UserValidator<ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false };
        this.UserTokenProvider = new EmailTokenProvider<ApplicationUser, string>();
        this.EmailService = new EmailService();
    }

} 

关于c# - 生成密码重置 token 时出现身份 IUserEmailStore 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24825851/

相关文章:

c# - 了解 ActionFilterAttribute 检查是否为空

javascript - 验证验证组

c# - 如何在 C# 中对开放类型进行泛型多态?

c# - 如何拥有字典的迭代器?

c# - C# 中的内存使用情况

c# - 如何从 JavaScript 调用方法背后的代码

c# - 从页面读取 XML 响应

c# - 将 2 List<string> 与 LIKE 子句进行比较

c# - datasource是asp.net中克隆生成的Datatable时如何绑定(bind)gridview允许分页

应用程序启动时 ASP.NET WebForms "Length cannot be less than 0 or exceed input length."