asp.net core通过读取配置文件来动态生成接口


如果希望接口是每次通过配置文件生成的,这样设计一些低代码的方式来获得接口。

系统目录结构:

启动配置代码:

csharp 复制代码
using Microsoft.AspNetCore.Hosting;
using System.Configuration;
using System.Data.Entity;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using AutoMapDBCreateApi.Models;
using AutoMapDBCreateApi.Filters;

var builder = WebApplication.CreateBuilder(args);

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

var endpointsConfig = configuration.GetSection("Endpoints").Get<List<EndpointConfig>>();

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "动态接口管理Swagger平台", Version = "v1" });

    // 为 Swagger 设置xml文档注释路径
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);

    // 添加自定义扩展
    c.DocumentFilter<DynamicEndpointsOperationFilter>();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "动态接口管理Swagger平台");
    });
}
app.UseRouting();
//app.UseAuthentication(); // 启用认证中间件
//app.UseAuthorization(); // 启用授权中间件

app.UseEndpoints(endpoints =>
{
    foreach (var endpointConfig in endpointsConfig)
    {
        // 动态生成接口
        endpoints.MapMethods(endpointConfig.Path, new[] { endpointConfig.Method }, async context =>
        {
            //var id = context.Request.RouteValues["id"] as string;
            var routeParams = context.Request.RouteValues;  // 获取路由参数
            var queryParams = context.Request.Query;  // 获取查询参数
            var headerParams = context.Request.Headers;  // 获取请求头参数
            var id = queryParams["id"].FirstOrDefault();
            if (!string.IsNullOrEmpty(id))
            {
                await context.Response.WriteAsync("id:"+id+","+endpointConfig.Response);
            }
            // 返回预定义的响应
            await context.Response.WriteAsync(endpointConfig.Response);
        });
    }
});

app.MapControllers();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.Run();

动态接口过滤器代码:

csharp 复制代码
using AutoMapDBCreateApi.Models;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace AutoMapDBCreateApi.Filters
{
    /// <summary>
    /// 动态接口过滤器
    /// </summary>
    public class DynamicEndpointsOperationFilter : IDocumentFilter
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="context"></param>
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            // 读取接口配置数据,例如从数据库或配置文件中获取
            //    var endpointsConfig = new List<EndpointConfig>
            //{
            //    new EndpointConfig { Path = "/api/customers", Method = "GET", Summary = "Dynamic Customers Endpoint", Description = "This is a dynamically generated endpoint for customers." },
            //    new EndpointConfig { Path = "/api/orders", Method = "POST", Summary = "Dynamic Orders Endpoint", Description = "This is a dynamically generated endpoint for orders." }
            //};

            var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

            // 读取接口配置数据
            var endpointsConfig = configuration.GetSection("Endpoints").Get<List<EndpointConfig>>();

            foreach (var endpointConfig in endpointsConfig)
            {
                // 创建动态生成的接口
                var path = endpointConfig.Path;
                var method = endpointConfig.Method;

                OpenApiOperation operation;

                if (endpointConfig.Path.Contains("/api/customers"))
                {
                    operation = new OpenApiOperation
                    {
                        Tags = new List<OpenApiTag> { new OpenApiTag { Name = endpointConfig.GroupName } },
                        Summary = endpointConfig.Summary,
                        Description = endpointConfig.Description,
                        Parameters = new List<OpenApiParameter>() { new OpenApiParameter() { AllowEmptyValue = false,
                        Required=true,
                            Name = "id" ,
                            Description="传入的Id",
                            Schema=new OpenApiSchema() { Type="Int"},In=ParameterLocation.Query } },
                        Responses = new OpenApiResponses()
                    };
                }
                else
                {
                    operation = new OpenApiOperation
                    {
                        Tags = new List<OpenApiTag> { new OpenApiTag { Name = endpointConfig.GroupName } },
                        Summary = endpointConfig.Summary,
                        Description = endpointConfig.Description,
                        Parameters = new List<OpenApiParameter>(),
                        Responses = new OpenApiResponses()
                    };
                }

                // 根据需要添加请求参数、响应定义等
                swaggerDoc.Paths.Add(path, new OpenApiPathItem
                {
                    Operations = new Dictionary<OperationType, OpenApiOperation>
                {
                    { GetOperationType(method), operation }
                }
                });
            }
        }

        private OperationType GetOperationType(string method)
        {
            return method switch
            {
                "GET" => OperationType.Get,
                "POST" => OperationType.Post,
                "PUT" => OperationType.Put,
                "DELETE" => OperationType.Delete,
                _ => throw new NotSupportedException($"Unsupported HTTP method: {method}")
            };
        }

    }
}
相关推荐
2401_857622662 小时前
SpringBoot框架下校园资料库的构建与优化
spring boot·后端·php
2402_857589362 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
哎呦没3 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
_.Switch4 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
杨哥带你写代码5 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
AskHarries6 小时前
读《show your work》的一点感悟
后端
A尘埃6 小时前
SpringBoot的数据访问
java·spring boot·后端
yang-23076 小时前
端口冲突的解决方案以及SpringBoot自动检测可用端口demo
java·spring boot·后端
Marst Code6 小时前
(Django)初步使用
后端·python·django
代码之光_19806 小时前
SpringBoot校园资料分享平台:设计与实现
java·spring boot·后端