您好,登錄后才能下訂單哦!
小編給大家分享一下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; }); }
看完了這篇文章,相信你對“ASP.NET Core中WebApi如何返回統一格式參數”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。