1

我遇到困难的方法是:

if (ModelState.IsValid)
{
    var user = new User { UserName = model.Email, Email = model.Email };
    IdentityResult result = null;
    try
    {
        result = await this._userManager.CreateAsync(user, model.Password).Result;
    }
    catch (Exception ex)
    {
    }

    if (result != null && result.Succeeded)
    {
      // not important code
    }
    AddErrors(result);
}

// If we got this far, something failed, redisplay form
return View(model);

我相信该方法存在错误CreateAsync(TUser user, string passwor)(Microsoft.AspNet.Identity、Microsoft.AspNet.IdentityCore.dll、v2.0.0.0)。如果我使用密码验证器配置用户管理器并且密码未验证,则没有异常(良好路径)并且IdentityResult看起来像

Errors      {string[1]}
- string[]  {string[1]}
-- [0]      "Passwords must have at least...."

但是,如果传入现有用户,而不是好的 IdentityResult,则该方法会引发EntityValidationErrors异常(错误路径)。我想把上面的代码放回原来的没有尝试捕获并真正依赖IdentityResult

if (ModelState.IsValid)
{
    var user = new User { UserName = model.Email, Email = model.Email };

    var result = this._userManager.CreateAsync(user, model.Password);

    if (result.Succeeded)
    {
      // not important code
    }
    AddErrors(result);
}

并覆盖该CreateAsync()方法:

public override Task<IdentityResult> CreateAsync(User user, string password)
{
    Task<IdentityResult> result = null;
    try
    {
        var ir = base.CreateAsync(user, password);

        return ??;
    }
    catch (DbEntityValidationException ex)
    {
        var errors = ex.EntityValidationErrors
            .Where(e => e.IsValid)
            .SelectMany(e => e.ValidationErrors)
            .Select(e => e.ErrorMessage)
            .ToArray();
        var ir = new IdentityResult(errors);

        return ??;
    }

    return result;
}

但是,我根本不知道如何返回任务,也不知道这是否是解决问题的正确方向。

我想我可以这样做,但使用另一个只会返回一个值的线程,似乎绝对是错误的路线。

result = Task.Factory.StartNew(() =>
{
  return ir;
});
4

1 回答 1

2

只需让你的方法asyncawait有问题的任务,然后在catch子句中返回替代值。

public override async Task<IdentityResult> CreateAsync(User user, string password)
{
    try
    {
        return await base.CreateAsync(user, password);
    }
    catch (DbEntityValidationException ex)
    {
        var errors = ex.EntityValidationErrors
            .Where(e => e.IsValid)
            .SelectMany(e => e.ValidationErrors)
            .Select(e => e.ErrorMessage)
            .ToArray();
        return new IdentityResult(errors);
    }
}
于 2014-05-14T19:59:04.027 回答