IdentityResult到ActionResult

时间:2016-06-29 13:35:48

标签: asp.net-core

是否有一种简单的方法可以将IdentityResult转换为IActionResult并考虑到错误?

2 个答案:

答案 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();
}