在开发过程中我们的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"
}
}