using Microsoft.AspNetCore.Authentication;
|
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.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
using Utility.Entity;
|
|
namespace Utility
|
{
|
public class ApiResponseActionFilter : IAsyncResultFilter
|
{
|
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
|
{
|
if (context.Result is ObjectResult objectResult)
|
{
|
if (objectResult.StatusCode != null)
|
{
|
await next();
|
return;
|
}
|
ApiResponse<object> apiResponse;
|
if (objectResult.Value is SqlSugarPagedList)
|
{
|
apiResponse = new ApiResponse<object>(
|
0, "请求成功",
|
((SqlSugarPagedList)objectResult.Value).Items,
|
((SqlSugarPagedList)objectResult.Value).Total);
|
}
|
else
|
{
|
apiResponse = new ApiResponse<object>(
|
0, "请求成功",
|
objectResult.Value);
|
}
|
var json = JsonConvert.SerializeObject(apiResponse);
|
context.HttpContext.Response.ContentType = "application/json";
|
context.HttpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
|
|
context.Result = new ObjectResult(apiResponse);
|
//await context.HttpContext.Response.WriteAsync(json);
|
|
}
|
else if (context.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);
|
context.Result = new ObjectResult(apiResponse);
|
//await context.HttpContext.Response.WriteAsync(json);
|
}
|
await next();
|
}
|
}
|
}
|