詳解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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- ASP.NET Core WebApi版本控制的實現(xiàn)
- 詳解如何在ASP.NET Core Web API中以三種方式返回數(shù)據(jù)
- asp.net core webapi文件上傳功能的實現(xiàn)
- 詳解ASP.NET Core Web Api之JWT刷新Token
- 在IIS上部署ASP.NET Core Web API的方法步驟
- ASP.NET Core奇淫技巧之動態(tài)WebApi的實現(xiàn)
- ASP.NET Core WebAPI實現(xiàn)本地化(單資源文件)
- Asp.Net Core使用swagger生成api文檔的完整步驟
- ASP.NET Core實現(xiàn)自定義WebApi模型驗證詳解
- Asp.Net Core 調(diào)用第三方Open API查詢物流數(shù)據(jù)的示例
相關(guān)文章
如何使用ASP.NET MiniAPI 調(diào)試未匹配請求路徑
ASP.NET MiniAPI是一個輕量級的Web API框架,它可以讓我們快速地構(gòu)建和部署RESTful服務,本文給大家介紹使用ASP.NET MiniAPI 調(diào)試未匹配請求路徑的方法,感興趣的朋友一起看看吧2024-01-01