net6全局api过滤统一返回格式

在开发过程中我们的api接口返回格式如果不统一的话,前端去解析起来可能会比较麻烦,我们应该统一返回形式,固定数据的存放。

创建特性

using Identification.Domain.Shared.CustomAttribute.Model;
using Identification.Domain.Shared.CustomAttribute;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Net;

namespace Test.Host.Common.CustomAttribute
{
    public class MyActionFilterAttribute : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                List<string> errorList = new List<string>();
                var result = context.ModelState.Keys
                    .SelectMany(
                        key => context.ModelState[key]!.Errors.Select(x => new ValidationError() { fields = key, data = x.ErrorMessage }))
                    .ToList();

                result.ForEach(x =>
                {
                    errorList.Add($"{x.fields}:{x.data}");
                });
                context.Result = new ObjectResult(new BaseResultModel
                {
                    code = 400,
                    message = errorList.Count > 0 ? string.Join(',', errorList) : "error:请参考详细信息",
                    data = result
                });
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        { 
            // 如果方法上有 SkipMyActionFilterAttribute 特性,则跳过过滤器的处理  
            if (context.ActionDescriptor.EndpointMetadata.Any(em => em is SkipMyActionFilterAttribute)) return; 

            var statusCode = HttpStatusCode.OK;
            var result = context.Result as ObjectResult;
            context.Result = new OkObjectResult(new BaseResultModel
            {
                code = (int)statusCode,
                message = "success",
                data = result?.Value
            });
        }
    }
}

注册

在Program.cs文件中注册特性类

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(options =>
{
    options.Filters.Add<MyActionFilterAttribute>();//控制器方法的过滤
});

查看效果

{
	"code": 200,
	"message": "success",
	"data": {
		"access_token": "eyJhbGciOiJodHRwOi8vd3d3LnczL",
		"refresh_token": "edc123-259f-4f0d-9fa0-9375c17d8c64",
		"expires_in": 86400,
		"token_type": "Bearer"
	}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

香煎三文鱼

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值