.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. Vue.js之计算属性(computed)、属性监听(watch)与方法选项(methods)

    vue.js官网:https://cn.vuejs.org/v2/guide/components-registration.html 一.计算属性-computed 1. 作用:能够避免数据冗余,通 ...

  2. react-motion 动画案例介绍

    第一个案例:Motion组件 import React,{Component} from 'react'; import {Motion,spring,presets} from 'react-mot ...

  3. freeswitch插件式模块接口实现方式

    概述 freeswitch的外围模块是插件式的,可以动态的加载和卸载,使用起来非常的灵活和方便. 如果我们自己来设计一个开源的代码框架,相信这种插件式的模块结构是非常适合多人合作的模式. 本文对fs的 ...

  4. background-position:color url(image) -left -up no-repeat;

    转载请注明来源:https://www.cnblogs.com/hookjc/ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transit ...

  5. android 安装gcc环境

    看到了一篇关于Android上利用终端来使用gcc编译C/C++源程序的文章,我感到无比兴奋,所以立刻将我自己的安装过程记下来.那个后记也很有用的. gcc编译源代码需要创建临时文件,而gcc又只能安 ...

  6. Spring Boot一些基础配置

    1.定制banner,Spring Boot项目在启动的时候会有一个默认的启动图案: . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ...

  7. Java微信公众号服务器配置-验证Token

    一.填写服务器配置 首先我们需要在微信公众平台上填写服务器配置 重点内容    服务器地址URL(一定要外网能访问的到)        在我们提交配置的时候,微信会发送GET请求到URL上,      ...

  8. Shell条件练习题

    Shell条件练习题 目录 Shell条件练习题 1.检查用户家目录中的 test.sh 文件是否存在,并且检查是否有执行权限 2.提示用户输入100米赛跑的秒数,要求判断秒数大于0且小于等于10秒的 ...

  9. 浅谈Java之属性赋值的先后顺序

    首先,什么是属性? 属性也叫作成员变量,是类的组成部分之一. 我们都知道Java一个类可以包含有: 属性,或者成员变量 构造器 方法,或者叫函数 代码块,或者叫程序段 内部类 那么结合这些,我们就有了 ...

  10. CopyOnWriteList揭秘

    List的并发容器-CopyOnWriteList Vector和SynchronizedList ArrayList是用来代替Vector,Vector是线程安全的容器,因为它在方法上都加上了syn ...