using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc.Filters;
|
using NetTaste;
|
using Newtonsoft.Json;
|
using System;
|
using System.Collections.Generic;
|
using System.Text;
|
using System.Threading.Tasks;
|
using Utility.Entity;
|
using Utility.Extension;
|
|
namespace Utility
|
{
|
public class ApiResponseActionFilter : IAsyncActionFilter
|
{
|
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
{
|
// 在执行动作之前的逻辑
|
var resultContext = await next(); // 执行动作方法并获取执行结果
|
|
// 在执行动作之后的逻辑
|
if (resultContext.Result is ObjectResult objectResult)
|
{
|
ApiResponse<object> apiResponse;
|
if (objectResult.Value is SqlSugarPagedList)
|
{
|
apiResponse = new ApiResponse<object>(
|
context.HttpContext.Response.StatusCode == 200 ? 0 : 1,
|
context.HttpContext.Response.StatusCode == 200 ? "请求成功" : "错误",
|
((SqlSugarPagedList)objectResult.Value).Items,
|
((SqlSugarPagedList)objectResult.Value).Total);
|
}
|
else
|
{
|
apiResponse = new ApiResponse<object>(
|
context.HttpContext.Response.StatusCode == 200 ? 0 : 1,
|
context.HttpContext.Response.StatusCode == 200 ? "请求成功" : "错误",
|
objectResult.Value);
|
}
|
var json = JsonConvert.SerializeObject(apiResponse);
|
context.HttpContext.Response.ContentType = "application/json";
|
context.HttpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
|
|
await context.HttpContext.Response.WriteAsync(json);
|
}
|
if (resultContext.Result is EmptyResult)
|
{
|
var apiResponse = new ApiResponse<object>(
|
context.HttpContext.Response.StatusCode == 200 ? 0 : 1,
|
context.HttpContext.Response.StatusCode == 200 ? "请求成功" : "错误",
|
"请求成功"
|
);
|
|
var json = JsonConvert.SerializeObject(apiResponse);
|
context.HttpContext.Response.ContentType = "application/json";
|
context.HttpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
|
|
await context.HttpContext.Response.WriteAsync(json);
|
}
|
}
|
}
|
}
|