【问题标题】:StatusCode Helper MethodStatusCode 辅助方法
【发布时间】:2017-10-08 07:11:34
【问题描述】:

我正在为我的 ASP.NET Core 2.0 API 方法创建一个辅助方法,该方法将根据我从后端逻辑获得的响应返回一个状态代码。我正在创建辅助方法来消除多个 API 方法中的重复代码。

我不确定我的辅助方法需要返回什么数据类型。到目前为止,这是我所得到的:

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吗?

【问题讨论】:

    标签: asp.net-web-api asp.net-core asp.net-core-webapi


    【解决方案1】:

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

    public const int Status200OK = 200;
    

    所以声明int

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

    如果您的目标是直接从控制器返回,您可以定义一个基本控制器。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2012-12-30
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多