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

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

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

    }
}

  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬砖的诗人Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值