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

在这里插入图片描述
asp.net core通过读取配置文件来动态生成接口_第1张图片
如果希望接口是每次通过配置文件生成的,这样设计一些低代码的方式来获得接口。
系统目录结构:
asp.net core通过读取配置文件来动态生成接口_第2张图片
启动配置代码:

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();

动态接口过滤器代码:

using AutoMapDBCreateApi.Models;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

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

        /// 
        /// 
        /// 
        /// 
        /// 
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            // 读取接口配置数据,例如从数据库或配置文件中获取
            //    var endpointsConfig = new List
            //{
            //    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}")
            };
        }

    }
}

你可能感兴趣的:(C#,asp.net,后端)