這篇文章主要介紹了詳解ASP.NET Core WebApi 返回統一格式參數,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
業務場景:
業務需求要求,需要對 WebApi 接口服務統一返回參數,也就是把實際的結果用一定的格式包裹起來,比如下面格式:
{ "response":{ "code":200, "msg":"Remote service error", "result":"" } }
具體實現:
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; public class WebApiResultMiddleware : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext context) { //根據實際需求進行具體實現 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; }); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。