hwh
2024-06-19 eede0d8477e7117e652b870cb29ef78a95b7f38a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
    {
 
    }
}