亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解ASP.NET Core WebApi 返回統(tǒng)一格式參數(shù)

 更新時間:2018年11月27日 11:02:53   作者:田園里的蟋蟀  
這篇文章主要介紹了詳解ASP.NET Core WebApi 返回統(tǒng)一格式參數(shù),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

業(yè)務場景:

業(yè)務需求要求,需要對 WebApi 接口服務統(tǒng)一返回參數(shù),也就是把實際的結(jié)果用一定的格式包裹起來,比如下面格式:

{
  "response":{
    "code":200,
    "msg":"Remote service error",
    "result":""
  }
}

具體實現(xiàn):

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class WebApiResultMiddleware : ActionFilterAttribute
{
  public override void OnResultExecuting(ResultExecutingContext context)
  {
    //根據(jù)實際需求進行具體實現(xiàn)
    if (context.Result is ObjectResult)
    {
      var objectResult = context.Result as ObjectResult;
      if (objectResult.Value == null)
      {
        context.Result = new ObjectResult(new { code = 404, sub_msg = "未找到資源", msg = "" });
      }
      else
      {
        context.Result = new ObjectResult(new { code = 200, msg = "", result = objectResult.Value });
      }
    }
    else if (context.Result is EmptyResult)
    {
      context.Result = new ObjectResult(new { code = 404, sub_msg = "未找到資源", msg = "" });
    }
    else if (context.Result is ContentResult)
    {
      context.Result = new ObjectResult(new { code = 200, msg = "", result= (context.Result as ContentResult).Content });
    }
    else if (context.Result is StatusCodeResult)
    {
      context.Result = new ObjectResult(new { code = (context.Result as StatusCodeResult).StatusCode, sub_msg = "", msg = "" });
    }
  }
}

Startup添加對應配置:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc(options =>
  {
    options.Filters.Add(typeof(WebApiResultMiddleware));
    options.RespectBrowserAcceptHeader = true;
  });
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論