ASP.NET Core 过滤器返回自定义响应数据
自定义返回类
public class ApiResponse { public int Code { get; set; } public string Message { get; set; } public object Data { get; set; } public ApiResponse(int code, string message, object data = null) { Code = code; Message = message; Data = data; } }
ApiResultFilterAttribute
public class ApiResultFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext context) { if (context.Result is ObjectResult objectResult) { var apiResponse = new ApiResponse(200, "成功", objectResult.Value); context.Result = new ObjectResult(apiResponse); } else if (context.Result is EmptyResult) { var apiResponse = new ApiResponse(200, "成功"); context.Result = new ObjectResult(apiResponse); } base.OnActionExecuted(context); } }
ApiExceptionFilterAttribute
public class ApiExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(ExceptionContext context) { var exceptionDetail = context.Exception.Message; var innerException = context.Exception.InnerException != null ? $" Inner exception: {context.Exception.InnerException.Message}" : string.Empty; var apiResponse = new ApiResponse(400, exceptionDetail + innerException); context.Result = new ObjectResult(apiResponse); context.ExceptionHandled = true; } }
在progarm.cs注册
builder.Services.AddControllers(options => { options.Filters.Add<ApiResultFilterAttribute>(); options.Filters.Add<ApiExceptionFilterAttribute>(); });
返回结果
正常:
异常: