2017-10-07 145 views
1

我爲我的ASP.NET Core 2.0 API方法創建了一個輔助方法,該方法將根據我從後端邏輯獲得的響應返回狀態碼。我創建了輔助方法來消除多個API方法中的重複代碼。StatusCode幫助程序方法

我不確定我的幫助器方法需要返回哪種數據類型。下面是我到目前爲止有:

public static StatusCodes GetHttpStatus(string type) 
{ 
    // I have some logic that I process here 
    switch(type) 
    { 
     case "Success": 
      return StatusCodes.Status200Ok; 
     case "Unauthorized": 
      return StatusCodes.Status401Unauthorized; 
    } 
} 

我想從我的API調用方法輔助方法:

public async Task<IActionResult> Get() 
{ 
    // Call my backend and get data 
    var response = await _myServiceMethod.GetData(); 

    if(response.Type == "Success") 
     return Ok(response.Data); 

    return HelperMethods.GetHttpStatus(response.type); 
} 

什麼,我需要從我GetHttpStatus()方法返回?是Microsoft.AspNetCore.Http.StatusCodes

回答

0

Microsoft.AspNetCore.Http.StatusCodes成員是int值。

public const int Status200OK = 200; 

所以聲明int

public static int GetHttpStatus(string type) 
{ 
    case "Success": 
     return StatusCodes.Status200OK; 
} 

如果您的目標是直接從Controller返回,您可以改爲定義一個基本控制器。

public abstract class BaseApiController<T> : Controller where T : MyApiContent 
{ 
    public virtual IActionResult ApiResult(string status, T content) 
    { 
     switch(status) 
     { 
      case "Success": 
       return Ok(content); 
      case "Unauthorized": 
       return Unauthorized(); 
     } 
    } 
} 

public class MyApiContent 
{ 
} 

public class MyApiController : BaseApiController<MyApiContent> 
{ 
    public async Task<IActionResult> Get() 
    { 
     MyApiContent content = await GetData(); 

     return ApiResult(content.type, content); 
    } 
}