如何在ASP.NET身份帐户控制器中创建一个方法返回我自己的错误消息?

时间:2015-10-22 05:08:08

标签: c# asp.net

控制器具有此功能:

private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }
            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
                if (ModelState.IsValid)
                {
                    // No ModelState errors are available to send, 
                    // so just return an empty BadRequest.
                    return BadRequest();
                }
                return BadRequest(ModelState);
            }
            return Ok();
        }

我有一个忘记密码方法,如果找不到用户名,我希望这会返回错误:

public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            var user = await UserManager.FindByNameAsync(model.UserName);
            if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            {
                // I want to return a BadRequest with message "Username not found"
                // What I think is needed is to put that message into result.Errors 
                // but I am not sure how to do that
                return GetErrorResult(result);
            }

1 个答案:

答案 0 :(得分:2)

您可以创建新的IdentityResult对象并将错误消息传递给ctor。 (它指定结果失败并向Errors属性添加错误消息)。

public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
{
    var user = await UserManager.FindByNameAsync(model.UserName);
    if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
    {
        IdentityResult result = new IdentityResult("Username not found");
        return GetErrorResult(result);
    }
}