.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统一接口返回值格式的更多相关文章

  1. 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】03、创建RESTful API,并统一处理返回值

    本节应用Spring对RESTful的支持,使用了如@RestController等注解实现RESTful控制器. 如果对Spring中的RESTful不太明白,请查看相关书籍 1.创建一个数据对象, ...

  2. 只需一步,在Spring Boot中统一Restful API返回值格式与统一处理异常

    ## 统一返回值 在前后端分离大行其道的今天,有一个统一的返回值格式不仅能使我们的接口看起来更漂亮,而且还可以使前端可以统一处理很多东西,避免很多问题的产生. 比较通用的返回值格式如下: ```jav ...

  3. Redis总结(五)缓存雪崩和缓存穿透等问题 Web API系列(三)统一异常处理 C#总结(一)AutoResetEvent的使用介绍(用AutoResetEvent实现同步) C#总结(二)事件Event 介绍总结 C#总结(三)DataGridView增加全选列 Web API系列(二)接口安全和参数校验 RabbitMQ学习系列(六): RabbitMQ 高可用集群

    Redis总结(五)缓存雪崩和缓存穿透等问题   前面讲过一些redis 缓存的使用和数据持久化.感兴趣的朋友可以看看之前的文章,http://www.cnblogs.com/zhangweizhon ...

  4. Web Api 接口返回值不困惑:返回值类型详解

    前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi的园友们速速动起来,跟着博主一起来学习吧.之前分享过一篇 WebApi 接口参数:传参详解,这篇博文内容本身很基础 ...

  5. ASP.NET WEB API微信支付通知接口,返回xml数据,微信服务器不识别问题

    原文:ASP.NET WEB API微信支付通知接口,返回xml数据,微信服务器不识别问题 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/MrTra ...

  6. Web API 2:Action的返回类型

    Web API 2:Action的返回类型 Web API控制器中的Action方法有如下几种返回类型: void HttpResponseMessage IHttpActionResult 其它类型 ...

  7. ASP.NET Web API 2:Action的返回类型

    Web API控制器中的Action方法有如下几种返回类型: void HttpResponseMessage IHttpActionResult 其它类型 基于上面几种不同的返回类型,Web API ...

  8. API 接口返回值

    API 接口返回值 https://blog.csdn.net/baple/article/details/52925772

  9. 腾讯微博API时间线相关接口返回的微博信息中head值使用问题

    腾讯微博API时间线相关接口返回的微博信息中head值表示作者头像url,这个链接直接访问并不能使用,需要再附加一个参数指定图片的大小(100.50),比如:[head]/100.

随机推荐

  1. salesforce零基础学习(一百一十一)custom metadata type数据获取方式更新

    本篇参考: https://developer.salesforce.com/docs/atlas.en-us.234.0.apexref.meta/apexref/apex_methods_syst ...

  2. 「JSOI2018」机器人

    在本题当中为了方便,我们将坐标范围改至 \((0 \sim n - 1, 0 \sim m - 1)\),行走即可视作任意一维在模意义下 \(+1\). 同时,注意到一个位置只能经过一次,则可以令 \ ...

  3. js读取txt文件并下载

    //我在vue中测试, 可行, 这个只适用于google浏览器, ie需要xObject对象 // 下载txt if (/(txt)$/.test(name[1])) { var xhr = new ...

  4. 【转】linux shell编程实例总结

    查找当前目录中所有大于500M的文件,把这些文件名写到一个文本文件中,并统计其个数 find ./ -size +500M -type f | tee file_list | wc 在目录/tmp下找 ...

  5. oracle查看当前正在使用的数据库

    select name from V$DATABASE; 也可以用 select SYS_CONTEXT('USERENV','INSTANCE_NAME') from dual;

  6. k8s之Pod基础概念

    1. 资源限制 Pod是kubernetes中最小的资源管理组件,Pod也是最小化运行容器化应用的资源对象.一个Pod代表着集群中运行的一个进程.kubernetes中其他大多数组件都是围绕着Pod来 ...

  7. 社交网络分析的 R 基础:(六)绘图操作

    R 语言强大的可视化功能在科学研究中非常受欢迎,丰富的类库使得 R 语言可以绘制各种各样的图表.当然这些与本章内容毫无关系,因为笔者对绘制图表了解有限,仅限于能用的程度.接下来的内容无需额外安装任何包 ...

  8. Jetpack的ViewModel与LiveData

    本文基于SDK 29 一.ViewModel与LiveData的作用: 1.viewModel: 数据共享,屏幕旋转不丢失数据,并且在Activity与Fragment之间共享数据. 2.LiveDa ...

  9. NFS共享Nginx网页根目录(自动部署)

    IP HOSTNAME SERVICE SYSTEM 192.168.131.132 proxy-nfs nginx+nfs-server CentOS 7.6 192.168.131.131 ngi ...

  10. 私有化轻量级持续集成部署方案--04-私有代码仓库服务-Gitea

    提示:本系列笔记全部存在于 Github, 可以直接在 Github 查看全部笔记 企业级最流行的私有代码仓库是 Gitlab, 一开始我也打算部署 Gitlab作为私有代码仓库. 但部署完 d 成后 ...