.net6的webapi项目统一封装返回值

cs 复制代码
/// <summary>
/// 封装工厂后台的返回数据
/// </summary>
public class FactoryResultFilterAttribute : ResultFilterAttribute
{
    /// <summary>
    /// 如果只是返回Task的接口,会自动封装成CommonResponse
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        if (!context.ActionDescriptor.EndpointMetadata.Any(x => x.GetType().Equals(typeof(NoResultFilterAttribute))))
        {
            if (context.Result.GetType() == typeof(EmptyResult))
            {
                var res = new CommonResponse();
                context.Result = new JsonResult(res)
                {
                    ContentType = "application/json",
                    StatusCode = 200,
                };
            }
            else if ((context.HttpContext.Request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase) || context.HttpContext.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) && context.Result is ObjectResult)
            {
                var result = (ObjectResult)context.Result;
                var res = new CommonResponse<Object>
                {
                    Data = result.Value,
                };
                context.Result = new JsonResult(res)
                {
                    ContentType = "application/json",
                    StatusCode = 200,
                };
            }
        }
        await next.Invoke();
    }

}
  1. 统一包装返回参数,使用过滤器ResultFilterAttribute来实现,OnResultExecutionAsync中可以处理所有Get和Post类型接口返回的数据,用CommonResponse类包装一下。

CommonResponse类主要用来返回Code(200表示成功)和Message(访问失败的原因)

  1. 这里配合ExceptionFilterAttribute一起用,用来捕捉错误BusinessException,这样业务代码出现错误后,直接throw new BusinessException("金额不能为0"),就会被过滤器自动捕捉并封装成CommonResponse返回给前端,方便前端统一处理。
cs 复制代码
/// <summary>
/// 业务类型错误
/// </summary>
public class BusinessException : Exception
{
    public BusinessException() : base("数据不存在")
    {
    }
    public BusinessException(string message) : base(message)
    {

    }
}
cs 复制代码
/// <summary>
/// 通用的异常处理
/// </summary>
public class FactoryExceptionFilterAttribute : ExceptionFilterAttribute
{
    private readonly ILogger<FactoryExceptionFilterAttribute> _logger;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    public FactoryExceptionFilterAttribute(ILogger<FactoryExceptionFilterAttribute> logger)
    {
        _logger = logger;
    }
    /// <summary>
    /// 通用api接口异常处理
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task OnExceptionAsync(ExceptionContext context)
    {
        if (!context.ExceptionHandled)
        {
            Exception exception = context.Exception;
            if (exception is BusinessException)
            {
                context.Result = new JsonResult(new CommonResponse(exception.Message));
            }
            else if (exception is ValidationException)
            {
                ValidationException? e = exception as ValidationException;
                context.Result = new JsonResult(new CommonResponse(e?.Errors.FirstOrDefault()?.ErrorMessage ?? ""));
            }
            else
            {
                var res = new CommonResponse
                {
                    Code = ResCode.ServerError,
                    Message = "请求错误"
                };
                exception.Log(context.HttpContext);
                _logger.LogError(exception.Message);
                context.Result = new JsonResult(res);
            }
        }
        context.ExceptionHandled = true;
        return Task.CompletedTask;
    }
}
相关推荐
界面开发小八哥12 小时前
界面控件DevExpress WPF中文教程:Data Grid - 绑定数据
ui·.net·wpf·界面控件·devexpress·ui开发
BIGFISH201914 小时前
上下相机引导贴合的标定(绝对坐标方式)
c#
AlexZhao18915 小时前
.NET中联合类型的实现(OneOf框架核心机理讲解)
后端·.net
燃尽了,可无18 小时前
C#基础编程核心知识点总结
开发语言·c#
我不是程序猿儿20 小时前
【C#】观察者模式 + UI 线程调度、委托讲解
观察者模式·ui·c#
专注VB编程开发20年20 小时前
c# .net支持 NativeAOT 或 Trimming 的库是什么原理
前端·javascript·c#·.net
钢铁男儿21 小时前
C# 简单工厂模式(简单工厂模式如何工作)
前端·c#·简单工厂模式
isyoungboy1 天前
c#实现鼠标mousemove事件抽稀,避免大数据阻塞网络
c#·计算机外设·远程桌面·deskflow
一枚小小程序员哈1 天前
基于asp.net 的在线餐饮订餐系统的设计与实现/基于c#的网上订餐系统/餐厅管理系统
后端·c#·asp.net
好望角雾眠1 天前
第三阶段数据库-7:sql中函数,运算符,常用关键字
数据库·笔记·sql·学习·sqlserver·c#