控制器具有此功能:
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);
}
答案 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);
}
}