2020/02/01, ASP.NET Core 3.1, VS2019

摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构【11-WebApi统一处理返回值、异常】

使用IExceptionFilter过滤器实现异常统一处理,使用IResultFilter过滤器实现统一处理返回值

文章目录

此分支项目代码

本章节介绍了使用IExceptionFilter实现异常统一处理,使用IResultFilter实现统一处理返回值

添加异常过滤器

MS.WebApi应用程序中新建Filters文件夹,在该文件夹下新建ApiExceptionFilter.cs类:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using MS.Component.Aop; namespace MS.WebApi.Filters
{
/// <summary>
/// api异常过滤器
/// </summary>
public class ApiExceptionFilter : IExceptionFilter
{
private readonly ILogger<ApiExceptionFilter> _logger; public ApiExceptionFilter(ILogger<ApiExceptionFilter> logger)
{
_logger = logger;
} public void OnException(ExceptionContext context)
{
string methodInfo = $"{context.RouteData.Values["controller"] as string}Controller.{context.RouteData.Values["action"] as string}:{context.HttpContext.Request.Method}"; //如果不是AopHandledException异常,则可能没有记录过日志,进行日志记录
if (!(context.Exception is AopHandledException))
{
_logger.LogError(context.Exception, "执行{0}时发生错误!", methodInfo);
}
context.Result = new JsonResult(new
{
status = 501,
data = "服务器出错"
});
}
}
}

如果controller在执行过程中遇到错误,则会被过滤器捕获到,如果错误已经被LogAop(之前写的业务层的)处理过,那在ApiExceptionFilter中判断下就不处理了,最后统一返回501,提示服务器出错

添加结果过滤器

在Filters文件夹下新建ApiResultFilter.cs类:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System; namespace MS.WebApi.Filters
{
/// <summary>
/// 给api返回结果包一层状态码
/// </summary>
public class ApiResultFilter : IResultFilter
{
public void OnResultExecuting(ResultExecutingContext context)
{
if (context.Result != null)
{
if (context.Result is ObjectResult objectResult)
{
if (objectResult.DeclaredType is null) //返回的是IActionResult类型
{
context.Result = new JsonResult(new
{
status = objectResult.StatusCode,
data = objectResult.Value
});
}
else//返回的是string、List这种其他类型,此时没有statusCode,应尽量使用IActionResult类型
{
context.Result = new JsonResult(new
{
status = 200,
data = objectResult.Value
});
}
}
else if (context.Result is EmptyResult)
{
context.Result = new JsonResult(new
{
status = 200,
data = ""
});
}
else
{
throw new Exception($"未经处理的Result类型:{ context.Result.GetType().Name}");
} }
} public void OnResultExecuted(ResultExecutedContext context)
{
}
}
}
  • 就是对返回值又包了一层,status是状态码,data是数据

应用过滤器

Startup.cs类中,给AddControllers方法添加参数:

services.AddControllers(options =>
{
options.Filters.Add<ApiResultFilter>();
options.Filters.Add<ApiExceptionFilter>();
});

services.AddControllers();改成以上内容:

  • 这样做是全局应用,所有的controller都会应用上面两个过滤器
  • 如果只想部分应用,可以考虑使用Attribute类型的过滤器,请查阅官方文档-筛选器章节

至此,过滤器已应用成功,启动项目,打开Postman调用接口:



可以看到返回值已经包了一层

项目完成后,如下图所示

ASP.NET Core搭建多层网站架构【11-WebApi统一处理返回值、异常】的更多相关文章

  1. ASP.NET Core搭建多层网站架构【0-前言】

    2020/01/26, ASP.NET Core 3.1, VS2019 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构 目录 0-前言 1-项目结构分层建立 2-公共基 ...

  2. ASP.NET Core搭建多层网站架构【1-项目结构分层建立】

    2020/01/26, ASP.NET Core 3.1, VS2019 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构[1-项目结构分层建立] 文章目录 此分支项目代码 ...

  3. ASP.NET Core搭建多层网站架构【2-公共基础库】

    2020/01/28, ASP.NET Core 3.1, VS2019,Newtonsoft.Json 12.0.3, Microsoft.AspNetCore.Cryptography.KeyDe ...

  4. ASP.NET Core搭建多层网站架构【3-xUnit单元测试之简单方法测试】

    2020/01/28, ASP.NET Core 3.1, VS2019, xUnit 2.4.0 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构[3-xUnit单元测试 ...

  5. ASP.NET Core搭建多层网站架构【4-工作单元和仓储设计】

    2020/01/28, ASP.NET Core 3.1, VS2019, Microsoft.EntityFrameworkCore.Relational 3.1.1 摘要:基于ASP.NET Co ...

  6. ASP.NET Core搭建多层网站架构【5-网站数据库实体设计及映射配置】

    2020/01/29, ASP.NET Core 3.1, VS2019, EntityFrameworkCore 3.1.1, Microsoft.Extensions.Logging.Consol ...

  7. ASP.NET Core搭建多层网站架构【6-注册跨域、网站核心配置】

    2020/01/29, ASP.NET Core 3.1, VS2019, NLog.Web.AspNetCore 4.9.0 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站 ...

  8. ASP.NET Core搭建多层网站架构【7-使用NLog日志记录器】

    2020/01/29, ASP.NET Core 3.1, VS2019, NLog.Web.AspNetCore 4.9.0 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站 ...

  9. ASP.NET Core搭建多层网站架构【8.1-使用ViewModel注解验证】

    2020/01/29, ASP.NET Core 3.1, VS2019 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构[8.1-使用ViewModel注解验证] 使用V ...

随机推荐

  1. SpringBoot整合WEB开发--(三)文件上传

    文件上传: Java中文件上传一共涉及到两个组件,CommonsMultipartResolver和StandardServletMultipartResolver,其中CommonsMultipar ...

  2. Python_装饰器函数

    楔子 作为一个会写函数的python开发,我们从今天开始要去公司上班了.写了一个函数,就交给其他开发用了. def func1(): print('in func1') 季度末,公司的领导要给大家发绩 ...

  3. 矩阵快速幂+二分 poj3233

    #include <iostream> #include <cstdio> #include <string> #include <cstring> # ...

  4. Codeforces Round #624 (Div. 3) B. WeirdSort(排序)

    output standard output You are given an array aa of length nn . You are also given a set of distinct ...

  5. SpringMVC-时间类型转换

    在上一篇SpringMVC的提交表单中,我们使用的日期为String型,可以将日期转换为Date型,然后使用initBinder函数进行显示,具体代码如下: (1)首先更改User.java的birt ...

  6. schroeder reverb matlab实现

    原理参考:Natural sounding artificial reverberation combFilter.m: function output = combFilter(delay, gai ...

  7. git上传时出现ERROR: Repository not found.的解决办法

    今天在上传时出现错误,原因是之前更改了gitee上的个人空间地址,导致找不到.需要重新配置 https://gitee.com/help/articles/4114#article-header0

  8. Django框架-模型层

    Django框架-模型层 一.单表查询之必知必会13条 1.时间字段中的两个关键性参数 create_time = models.DateField() # 年月日 create_time = mod ...

  9. Vue.js 学习入门:介绍及安装

    Vue.js 是什么? Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架.与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用.Vue 的核心库只关注视图层 ...

  10. 【资源分享】Dll Injector(DLL注入器)

    *----------------------------------------------[下载区]----------------------------------------------* ...