using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Mvc.Controllers;
|
using Newtonsoft.Json;
|
using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
using Utility.Entity;
|
|
namespace Utility.Extension
|
{
|
public class ApiResponseMiddleware : IMiddleware
|
{
|
public ApiResponseMiddleware()
|
{
|
|
}
|
|
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
|
{
|
if (ShouldApplyApiResponseMiddleware(context))
|
{
|
// 捕获响应
|
var originalBodyStream = context.Response.Body;
|
|
using (var responseBody = new MemoryStream())
|
{
|
context.Response.Body = responseBody;
|
|
await next(context);
|
// 读取响应内容
|
context.Response.Body.Seek(0, SeekOrigin.Begin);
|
var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
|
context.Response.Body.Seek(0, SeekOrigin.Begin);
|
|
// 反序列化响应内容
|
object data = null;
|
if (!string.IsNullOrEmpty(body))
|
{
|
try
|
{
|
data = JsonConvert.DeserializeObject<object>(body);
|
}
|
catch (JsonException)
|
{
|
// 如果响应不是有效的JSON格式,直接将其作为字符串数据处理
|
data = body;
|
}
|
}
|
|
var apiResponse = new ApiResponse<object>(
|
code: context.Response.StatusCode == StatusCodes.Status200OK ? (int)ResponseEnum.Sucess : (int)ResponseEnum.Fail,
|
message: context.Response.StatusCode == StatusCodes.Status200OK ? "请求成功" : "",
|
data: data
|
);
|
|
var json = JsonConvert.SerializeObject(apiResponse);
|
context.Response.ContentType = "application/json";
|
context.Response.ContentLength = Encoding.UTF8.GetByteCount(json);
|
|
context.Response.Body = originalBodyStream;
|
await context.Response.WriteAsync(json);
|
}
|
}
|
else
|
{
|
await next(context);
|
}
|
}
|
private bool ShouldApplyApiResponseMiddleware(HttpContext context)
|
{
|
// 获取当前处理请求的控制器信息
|
var controllerActionDescriptor = context.GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>();
|
if (controllerActionDescriptor != null)
|
{
|
// 判断控制器是否带有 ResponseAttribute 特性
|
return controllerActionDescriptor.ControllerTypeInfo.IsDefined(typeof(UnifyResponseAttribute), inherit: true);
|
}
|
return false;
|
}
|
}
|
public static class ApiResponse
|
{
|
public static void UseApiResponse(this IApplicationBuilder app)
|
{
|
app.UseMiddleware<ApiResponseMiddleware>();
|
}
|
}
|
|
public class UnifyResponseAttribute : Attribute
|
{
|
|
}
|
}
|