.NetCore Web Api 利用ActionFilterAttribute统一接口返回值格式
.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
.NetCore Web Api 利用ActionFilterAttribute统一接口返回值格式的更多相关文章
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】03、创建RESTful API,并统一处理返回值
本节应用Spring对RESTful的支持,使用了如@RestController等注解实现RESTful控制器. 如果对Spring中的RESTful不太明白,请查看相关书籍 1.创建一个数据对象, ...
- 只需一步,在Spring Boot中统一Restful API返回值格式与统一处理异常
## 统一返回值 在前后端分离大行其道的今天,有一个统一的返回值格式不仅能使我们的接口看起来更漂亮,而且还可以使前端可以统一处理很多东西,避免很多问题的产生. 比较通用的返回值格式如下: ```jav ...
- Redis总结(五)缓存雪崩和缓存穿透等问题 Web API系列(三)统一异常处理 C#总结(一)AutoResetEvent的使用介绍(用AutoResetEvent实现同步) C#总结(二)事件Event 介绍总结 C#总结(三)DataGridView增加全选列 Web API系列(二)接口安全和参数校验 RabbitMQ学习系列(六): RabbitMQ 高可用集群
Redis总结(五)缓存雪崩和缓存穿透等问题 前面讲过一些redis 缓存的使用和数据持久化.感兴趣的朋友可以看看之前的文章,http://www.cnblogs.com/zhangweizhon ...
- Web Api 接口返回值不困惑:返回值类型详解
前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.之前分享过一篇 WebApi 接口参数:传参详解,这篇博文内容本身很基础 ...
- ASP.NET WEB API微信支付通知接口,返回xml数据,微信服务器不识别问题
原文:ASP.NET WEB API微信支付通知接口,返回xml数据,微信服务器不识别问题 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/MrTra ...
- Web API 2:Action的返回类型
Web API 2:Action的返回类型 Web API控制器中的Action方法有如下几种返回类型: void HttpResponseMessage IHttpActionResult 其它类型 ...
- ASP.NET Web API 2:Action的返回类型
Web API控制器中的Action方法有如下几种返回类型: void HttpResponseMessage IHttpActionResult 其它类型 基于上面几种不同的返回类型,Web API ...
- API 接口返回值
API 接口返回值 https://blog.csdn.net/baple/article/details/52925772
- 腾讯微博API时间线相关接口返回的微博信息中head值使用问题
腾讯微博API时间线相关接口返回的微博信息中head值表示作者头像url,这个链接直接访问并不能使用,需要再附加一个参数指定图片的大小(100.50),比如:[head]/100.
随机推荐
- 理解https中的安全及其实现原理
Google的一份网络上的 HTTPS 加密透明报告(数据截至2022年1月)中指出HTTPS 连接的普及率在过去几年激增,互联网上排名前 100 位的非 Google 网站HTTPS 使用情况为:9 ...
- 封装jar问题java.lang.SecurityException: Invalid signature file digest for Manifest main attributes以及maven依赖重提解决
1.jar包封装完成后,其他项目引用jar,启动时报错java.lang.SecurityException: Invalid signature file digest for Manifest m ...
- C3P0数据库连接池数据库插入中文乱码问题解决
问题描述 近期修改一个学生信息管理的JavaWeb项目,其数据库连接池使用了C3P0.在实际测试时,发现在学生信息模块添加中文学生信息会在数据库(MySQL)出现中文乱码问题. 如图所示: 问题分析 ...
- laravel中observe不能监听到updated事件原因
//这种方式不行Student::where('id', $request->student_id)->update($student); $findStudent = Student:: ...
- 无法加载 mcrypt (外链,英语) 扩展,请检查您的 PHP 配置。
转载请注明来源:https://www.cnblogs.com/hookjc/ 需要安装libcrytp,在下面的地址下载libmarypt: ftp://mcrypt.hellug.gr/pub/c ...
- 标签显示模式(display)
非洲黑人: 皮肤内黑色素含量高,以吸收阳光中的紫外线,保护皮肤内部结构免遭损害,头发象羊毛一样卷曲,使每根卷发周围都有许多空隙,空隙充满空气,卷发有隔热作用. 欧洲白人: 生活寒带或着是说常年温度较低 ...
- Lua 语言: 语法
转载请注明来源:https://www.cnblogs.com/hookjc/ -- 两个横线开始单行的注释 --[[ 加上两个[和]表示 多行的注释.--]] -------------- ...
- 初见Redis
Redis是什么,有什么特点和优势 Redis是一个开源用C语言编写的,基于内存,可以持久化,高性能的key-value数据库,并提供多种语言的API. 它也被称为数据结构服务器,因为值(value) ...
- 操作系统发展史 & 进程
今日内容 UDP协议 操作系统发展史 进程 单核情况下的进程调度 进程三状态图 同步异步 阻塞非阻塞 内容详细 一.UDP协议 1.什么是UDP协议 UDP是传输层的协议,功能即为在IP的数据报服务之 ...
- Solution Set - Stirling 数相关杂题
<好多题的题解> 「洛谷 P5408」第一类斯特林数·行 根据结论 \[x^{\overline{n}}=\sum_i{n\brack i}x^i, \] 我们只需要求出 \( ...