2016-06-29 36 views
0

有沒有簡單的方法將IdentityResult轉換爲IActionResult考慮到錯誤?IdentityResult to ActionResult

+1

他們是完全無關的概念,僅僅是因爲他們都有「結果」一詞並不意味着它們可以從一個轉換到另一個 –

回答

2

IdentityResult只是一個告訴你ASP.NET(Core)Identity操作是否成功的類,如果發生錯誤會提供錯誤消息,並且與實現接口的MVC Action的結果無關。

如果您使用的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); 
    } 
} 

當然,這可以進一步優化,以便您不必爲每個請求創建兩個對象,但這是一個練習留給你的; )

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