是否有一种简单的方法可以将IdentityResult
转换为IActionResult
并考虑到错误?
答案 0 :(得分:4)
IdentityResult
只是一个类,告诉您ASP.NET(核心)身份操作是否成功,如果出现错误,则会提供错误消息,与MVC Action的结果无关实现IActionResult
接口。
如果您使用WebApi / RestApi控制器,您可以将其翻译为
public IActionResult SomeActionName()
{
IdentityResult result = ...; // some identity operation
// all is okay, return http code 200
if(result.Success)
return Ok();
// error happened, return http code 400 + errors as json
return BadRequest(result.Errors);
}
或者,如果您非常懒惰,请编写自己的IActionResult
:
public class IdentityActionResult : IActionResult
{
private readonly IdentityResult identityResult;
public IdentityActionResult(IdentityResult identityResult)
{
this.identityResult = identityResult;
}
public Task ExecuteResultAsync(ActionContext context)
{
IActionResult actionResult = null;
if(identityResult.Success)
{
actionResult = new OkResult();
}
else
{
actionResult = new BadRequestObjectResult(identityResult.Errors);
}
return actionResult.Execute(context);
}
}
当然,这可以进一步优化,这样您就不必为每个请求创建两个IActionResult
个对象,但这是一个由您完成的练习;)
答案 1 :(得分:0)
您可以为IdentityResult
编写一个扩展方法,返回ObjectResult,如下所示:
public static class IdentityResultExtension
{
public static ObjectResult ToObjectResult(this IdentityResult result)
{
//
return new ObjectResult(result);
}
}
然后在行动中使用它:
public IActionResult YourAction()
{
IdentityResult result;
return result.ToObjectResult();
}