详解ASP.NET Core WebApi 返回统一格式参数
程序员文章站
2022-03-21 14:04:54
业务场景:
业务需求要求,需要对 webapi 接口服务统一返回参数,也就是把实际的结果用一定的格式包裹起来,比如下面格式:
{
"response"...
业务场景:
业务需求要求,需要对 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; }); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。