.net Core 使用Panda.DynamicWebApi动态构造路由

我们以前是通过创建controller来创建API,通过controller来显示的生成路由,这里我们讲解下如何不通过controller,构造API路由

  1. 安装
bash 复制代码
Panda.DynamicWebApi         1.2.2   1.2.2
Swashbuckle.AspNetCore      6.2.3   6.2.3
  1. 添加ServiceActionRouteFactory
csharp 复制代码
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Panda.DynamicWebApi;
using System.Reflection;

namespace DynamicControllerAPI.Dynamic
{
    public class ServiceActionRouteFactory : IActionRouteFactory
    {
        public string CreateActionRouteModel(string areaName, string controllerName, ActionModel action)
        {
            var controllerType = action.ActionMethod.DeclaringType;
            var serviceAttribute = controllerType.GetCustomAttribute<ServiceAttribute>();

            var _controllerName = serviceAttribute.ServiceName == string.Empty ? controllerName.Replace("Service", "") : serviceAttribute.ServiceName.Replace("Service", "");

            return $"api/{_controllerName}/{action.ActionName.Replace("Async", "")}";
        }
    }
}
  1. 添加ServiceLocalSelectController
csharp 复制代码
public class ServiceLocalSelectController : ISelectController
    {
        public bool IsController(Type type)
        {
            return type.IsPublic && type.GetCustomAttribute<ServiceAttribute>() != null;
        }
    }
  1. 添加注解
csharp 复制代码
[AttributeUsage(AttributeTargets.Class)]
    public class ServiceAttribute : Attribute
    {
        public ServiceAttribute()
        {
            ServiceName = string.Empty;
        }

        public ServiceAttribute(string serviceName)
        {
            ServiceName = serviceName;
        }

        public string ServiceName { get; }
    }
  1. 添加自定义服务
csharp 复制代码
namespace DynamicControllerAPI.Dynamic
{
    [Service("Other.Server")]
    public class OtherService
    {
        public readonly SingleClass _singleClass;

        public OtherService(SingleClass singleClass)
        {
            _singleClass = singleClass;
        }

        public int Create()
        {
            return 100;
        }

        public string GetUserName()
        {
            return _singleClass.getName();
        }

        public Task<int> TaskIntAsync()
        {
            return Task.FromResult(100);
        }
    }

    public class SingleClass

    {
        public string getName()
        {
            return "ellis";
        }
    }
}
  1. 修改工程文件DynamicControllerAPI.csproj添加如下

其中xml名字与工程名一致

bash 复制代码
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>bin\Debug\net6.0\DynamicControllerAPI.xml</DocumentationFile>
    <NoWarn>1701;1702;CS1591</NoWarn>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DocumentationFile>bin\Release\net6.0\DynamicControllerAPI.xml</DocumentationFile>
    <NoWarn>1701;1702;CS1591</NoWarn>
  </PropertyGroup>
  1. 依赖注入
bash 复制代码
builder.Services.AddDynamicWebApiCore<ServiceLocalSelectController, ServiceActionRouteFactory>();

// 注册Swagger生成器,定义一个和多个Swagger 文档
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo() { Title = "Dynamic WebApi", Version = "v1" });

    // 确保包含所有控制器
    options.DocInclusionPredicate((docName, description) => true);

    // XML 文件路径
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    Console.WriteLine($"XML Path: {xmlPath}"); // 调试路径输出
    options.IncludeXmlComments(xmlPath);
});

builder.Services.AddSingleton<SingleClass>();

// 启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();

// 启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dynamic WebApi v1");
});

官网

源码

相关推荐
海盗12345 天前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
啊这啊这 六弦之首12 天前
.NET Core跨平台的奥秘[中篇]:复用之殇
.netcore
心念枕惊13 天前
.NET CORE 授权进阶-角色、策略与动态权限实现
java·前端·.netcore
完美火龙篇 四月的友14 天前
通俗易懂,什么是.NET?什么是.NET Framework?什么是.NET Core?
.net·.netcore
时代的狂1 个月前
如何理解 C# 的 async 和 await
c#·.netcore·async·await
尼米棕熊1 个月前
.NET CORE认证模块-注册方案与请求认证探究
.netcore
鸠摩智首席音效师2 个月前
如何在 macOS 上安装 .NET Core ?
macos·.netcore
宝桥南山2 个月前
Microsoft Agent Framework(MAF) - 如何将workflow或者A2A client转换成一个AI Agent
microsoft·ai·微软·aigc·.net·.netcore
滴滴答答哒3 个月前
.NET Core 基于 AOP + Polly 实现数据库死锁自动重试
数据库·.netcore·sqlsugar
.NET修仙日记3 个月前
.NET EFCore批量插入性能优化实战:30秒 → 0.5秒
性能优化·c#·.net·.netcore·微软技术·efcore·踩坑实录