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

    }
}
相关推荐
齐 飞1 小时前
MongoDB笔记01-概念与安装
前端·数据库·笔记·后端·mongodb
LunarCod1 小时前
WorkFlow源码剖析——Communicator之TCPServer(中)
后端·workflow·c/c++·网络框架·源码剖析·高性能高并发
码农派大星。2 小时前
Spring Boot 配置文件
java·spring boot·后端
杜杜的man3 小时前
【go从零单排】go中的结构体struct和method
开发语言·后端·golang
幼儿园老大*3 小时前
走进 Go 语言基础语法
开发语言·后端·学习·golang·go
llllinuuu3 小时前
Go语言结构体、方法与接口
开发语言·后端·golang
cookies_s_s3 小时前
Golang--协程和管道
开发语言·后端·golang
为什么这亚子3 小时前
九、Go语言快速入门之map
运维·开发语言·后端·算法·云原生·golang·云计算
想进大厂的小王3 小时前
项目架构介绍以及Spring cloud、redis、mq 等组件的基本认识
redis·分布式·后端·spring cloud·微服务·架构
customer083 小时前
【开源免费】基于SpringBoot+Vue.JS医院管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·开源·intellij-idea