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}")
            };
        }

    }
}
相关推荐
刘大辉在路上3 小时前
突发!!!GitLab停止为中国大陆、港澳地区提供服务,60天内需迁移账号否则将被删除
git·后端·gitlab·版本管理·源代码管理
追逐时光者5 小时前
免费、简单、直观的数据库设计工具和 SQL 生成器
后端·mysql
初晴~5 小时前
【Redis分布式锁】高并发场景下秒杀业务的实现思路(集群模式)
java·数据库·redis·分布式·后端·spring·
盖世英雄酱581365 小时前
InnoDB 的页分裂和页合并
数据库·后端
小_太_阳6 小时前
Scala_【2】变量和数据类型
开发语言·后端·scala·intellij-idea
直裾6 小时前
scala借阅图书保存记录(三)
开发语言·后端·scala
星就前端叭7 小时前
【开源】一款基于Vue3 + WebRTC + Node + SRS + FFmpeg搭建的直播间项目
前端·后端·开源·webrtc
小林coding8 小时前
阿里云 Java 后端一面,什么难度?
java·后端·mysql·spring·阿里云
AI理性派思考者8 小时前
【保姆教程】手把手教你在Linux系统搭建早期alpha项目cysic的验证者&证明者
后端·github·gpu