详解ASP.NET Core WebApi 返回统一格式参数
业务场景:
业务需求要求,需要对WebApi接口服务统一返回参数,也就是把实际的结果用一定的格式包裹起来,比如下面格式:
{ "response":{ "code":200, "msg":"Remoteserviceerror", "result":"" } }
具体实现:
usingMicrosoft.AspNetCore.Mvc; usingMicrosoft.AspNetCore.Mvc.Filters; publicclassWebApiResultMiddleware:ActionFilterAttribute { publicoverridevoidOnResultExecuting(ResultExecutingContextcontext) { //根据实际需求进行具体实现 if(context.ResultisObjectResult) { varobjectResult=context.ResultasObjectResult; if(objectResult.Value==null) { context.Result=newObjectResult(new{code=404,sub_msg="未找到资源",msg=""}); } else { context.Result=newObjectResult(new{code=200,msg="",result=objectResult.Value}); } } elseif(context.ResultisEmptyResult) { context.Result=newObjectResult(new{code=404,sub_msg="未找到资源",msg=""}); } elseif(context.ResultisContentResult) { context.Result=newObjectResult(new{code=200,msg="",result=(context.ResultasContentResult).Content}); } elseif(context.ResultisStatusCodeResult) { context.Result=newObjectResult(new{code=(context.ResultasStatusCodeResult).StatusCode,sub_msg="",msg=""}); } } }
Startup添加对应配置:
publicvoidConfigureServices(IServiceCollectionservices) { services.AddMvc(options=> { options.Filters.Add(typeof(WebApiResultMiddleware)); options.RespectBrowserAcceptHeader=true; }); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。