.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;
    }
}
相关推荐
惜.己15 小时前
jmeter中java.net.ConnectException: Connection refused: connect
java·jmeter·.net
secondyoung17 小时前
Markdown转换为Word:Pandoc模板使用指南
开发语言·经验分享·笔记·c#·编辑器·word·markdown
andyguo1 天前
AI模型测评平台工程化实战十二讲(第五讲:大模型测评分享功能:安全、高效的结果展示与协作)
人工智能·安全·c#
关关长语1 天前
Dotnet接入AI通过Response创建一个简单控制台案例
人工智能·.net·ai dotnet
大飞pkz1 天前
【设计模式】访问者模式
开发语言·设计模式·c#·访问者模式
LateFrames1 天前
用 【C# + Winform + MediaPipe】 实现人脸468点识别
python·c#·.net·mediapipe
追逐时光者2 天前
精选 4 款开源免费、美观实用的 MAUI UI 组件库,助力轻松构建美观且功能丰富的应用程序!
后端·.net
R-G-B2 天前
【14】C#实战篇——C++动态库dll 接口函数将char* strErr字符串 传给C# ,并且在winform的MessageBox和listbox中显示。C++ string 日志传给 C#
c++·c#·strerr字符串传给c#·动态库dll传递字符串给c#·string日志传给c#·c++ string传给 c#·c++底层函数日志传给c#显示
我是唐青枫2 天前
深入掌握 FluentMigrator:C#.NET 数据库迁移框架详解
数据库·c#·.net
tiankongdeyige2 天前
Unity学习之C#的反射机制
学习·unity·c#