.NetCore Web Api 利用ActionFilterAttribute统一接口返回值格式
2024-09-22 11:33:23
.Net Core 同 Asp.Net MVC一样有几种过滤器,这里不再赘述每个过滤器的执行顺序与作用。
在实际项目开发过程中,统一API返回值格式对前端或第三方调用将是非常必要的,在.NetCore中我们可以通过ActionFilterAttribute来进行统一返回值的封装。
在封装之前我们需要考虑下面几个问题:
1,需要对哪些结果进行封装
我目前的做法是,只对ObjectResult进行封装,其他的类型:FileResult,ContentResult,EmptyResult,RedirectResult不予处理
2,对异常错误的封装
既然是统一返回值,当然也要考虑接口异常的问题了
但是不是所有的异常我们都需要返回给前端的,我们可能需要自定义一个业务异常,业务异常可以在前端进行友好提示,系统异常完全没必要抛出给前端或第三方,且需要对系统异常进行日志记录
项目结构:
Exceptions:自定义业务异常
Filters:自定义过滤器(统一结果封装,全局异常)
Models:统一结果实体
部分代码:
using System; namespace NetCoreCommonResult.Exceptions
{
/// <summary>
/// 自定义业务异常,可以由前端抛出友好的提示
/// </summary>
public class BizException:Exception
{
public BizException()
{ }
public BizException(string message):base(message)
{ }
public BizException(string message, Exception ex) : base(message, ex)
{ }
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters; namespace NetCoreCommonResult.Filters
{
public class CommonResultFilterAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
if (context.Result is ObjectResult objRst)
{
if (objRst.Value is Models.ApiResult)
return;
context.Result = new ObjectResult(new Models.ApiResult
{
Success = true,
Message = string.Empty,
Data = objRst.Value
});
}
}
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging; namespace NetCoreCommonResult.Filters
{
public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly ILogger<GlobalExceptionFilterAttribute> _logger;
public GlobalExceptionFilterAttribute(ILogger<GlobalExceptionFilterAttribute> logger)
{
_logger = logger;
}
public override void OnException(ExceptionContext context)
{
context.ExceptionHandled = true;
var isBizExp = context.Exception is Exceptions.BizException;
context.Result = new ObjectResult(new Models.ApiResult
{
Success = false,
Message = context.Exception.Message
});
//非业务异常记录errorLog,返回500状态码,前端通过捕获500状态码进行友好提示
if (isBizExp == false)
{
_logger.LogError(context.Exception, context.Exception.Message);
context.HttpContext.Response.StatusCode = 500;
}
base.OnException(context);
}
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; namespace NetCoreCommonResult
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddControllers(ops =>
{
//添加过滤器
ops.Filters.Add(new Filters.CommonResultFilterAttribute());
//GlobalExceptionFilterAttribute构造中注入其他服务,需要通过ServiceFilter添加
ops.Filters.Add(new Microsoft.AspNetCore.Mvc.ServiceFilterAttribute(typeof(Filters.GlobalExceptionFilterAttribute)));
});
//注册GlobalExceptionFilterAttribute
services.AddScoped<Filters.GlobalExceptionFilterAttribute>();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
} app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
平时不玩博客,不知道如何上传ZIP包,实例代码项目已经放到Gitee上了,地址:https://gitee.com/tang3402/net-core-samples.git
最新文章
- LeetCode&mdash;&mdash;Best Time to Buy and Sell Stock III (股票买卖时机问题3)
- Python for Infomatics 第12章 网络编程四(译)
- ie8兼容性(不支持trim 、readonly光标、乱码encodeURI())
- java目录
- FFT模板
- OutputFormat中OutputCommitter解析
- ABAP EXCEL 文件上传下载 用SMW0
- Paros抓包工具
- 【Spark2.0源码学习】-2.一切从脚本说起
- 芝麻HTTP:Python爬虫入门之正则表达式
- NGUI制作可滚动的文本框(摘,如有侵权,联系删除)
- MySQL中lock tables和unlock tables浅析
- reshape
- Python3基础-特别函数(map filter partial reduces sorted)实例学习
- loadrunner中web_reg_save_param和web_reg_save_param_ex的区别
- 使用phpStudy运行伊人集项目
- web 基础
- Checkpoints(第十一届河南省省赛真题)
- utime修改文件的存取,修改时间
- jQuery表格自动增加
热门文章
- LoadRunner编写socket性能测试脚本
- ApacheCN Angular 译文集 20211114 更新
- EKS助力小白实践云原生——通过k8s部署wordpress应用
- 揭秘CPU制造全过程
- CentOS 6.4x64安装部署zabbix-2.4.5
- NoSQL 之 Redis配置与优化
- 纯JS脚本发送HTTP请求
- 已完成的python项目-环境离线部署
- Vue中组件通信的几种方法(Vue3的7种和Vue2的12种组件通信)
- Kubernetes集群使用CentOS 7.6系统时kubelet日志含有“Reason:KubeletNotReady Message:PLEG is not healthy:”信息