sunpengfei
2025-08-01 6808e68b5d97cdb39aac1793e7fe30dfbecd7de2
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
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace FlexJobApi.Core
{
    public class CustomOperationIdFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            // 获取控制器和动作信息(Furion 中通过 ActionDescriptor 获取)
            if (context.ApiDescription.ActionDescriptor is not ControllerActionDescriptor actionDescriptor)
                return;
 
            // 自定义 OperationId 规则:例如“控制器名_动作名”
            var controllerName = actionDescriptor.ControllerName;
            var actionName = actionDescriptor.ActionName;
 
            // 设置最终的 OperationId
            operation.OperationId = $"{controllerName}-{actionName}";
 
            // 获取接口方法的返回类型(可能是 Task<ApiResult<T>> 或 ApiResult<T>)
            var returnType = context.MethodInfo.ReturnType;
 
            // 步骤 1:如果是 Task 或 Task<ApiResult<T>>,提取内部类型
            if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
            {
                returnType = returnType.GetGenericArguments()[0]; // 提取 Task<T> 中的 T
            }
 
            // 步骤 3:替换 Swagger 响应类型为 Data 的类型
            operation.Responses.Clear();
            operation.Responses.Add("200", new OpenApiResponse
            {
                Description = "操作成功",
                Content = new Dictionary<string, OpenApiMediaType>
                {
                    ["application/json"] = new OpenApiMediaType
                    {
                        Schema = context.SchemaGenerator.GenerateSchema(returnType, context.SchemaRepository)
                    }
                }
            });
        }
    }
}