在正常开发web api时需要返回固定格式的json数据,这样前端处理也方便,具体操作如下:
1.建立自定义过滤器
public class WebApiResultFilter : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext context) { if (context.Result is ObjectResult) { var result = context.Result as ObjectResult; if (result.Value == null) { context.Result = new ObjectResult(new { code = 0, msg = "未找到资源", data = "" }); } else { context.Result = new ObjectResult(new { code = 1, msg = "ok", data = result.Value }); } } else if (context.Result is EmptyResult) { context.Result = new ObjectResult(new { code = 0, msg = "未找到资源", data = "" }); } else if (context.Result is ContentResult) { context.Result = new ObjectResult(new { code = 1, msg = "ok", data = (context.Result as ContentResult).Content }); } else if (context.Result is StatusCodeResult) { context.Result = new ObjectResult(new { code = 1, msg = "ok", data = "" }); } } }
2.Startup.cs中注册过滤器
public void ConfigureServices(IServiceCollection services) { services.AddControllers(options => { options.Filters.Add(typeof(WebApiResultFilter)); }); }
3.实现效果:(这里推荐一个类似postman的测试工具:ApiPost)