利用 Panda.DynamicWebApi 快速构建动态 WebAPI
在 DDD 架构和微服务盛行的当下,我们时常会希望应用逻辑层能够直接“开口说话”——也就是说,服务类无需额外编写 Controller,就能直接暴露为标准 RESTful 风格的 Web API。Panda.DynamicWebApi 正是为此而生,它可以根据你的业务类自动生成 API 接口,完美集成 Swagger,同时性能无忧。
本文将带你了解如何使用 Panda.DynamicWebApi 快速构建 Web API,并介绍其核心配置与进阶用法。
一、Panda.DynamicWebApi 是什么?
Panda.DynamicWebApi 是一款受 ABP 框架启发的 .NET Core 扩展组件,可根据规则自动将你的服务类转化为 RESTful API,无需编写冗余的 Controller 代码。它默认集成 Swagger,API 文档清晰明了,且与手动创建 Controller 没有区别。
应用场景
最适用于 DDD(领域驱动设计)架构中的“应用服务层”。通过 Panda.DynamicWebApi,你可以让服务类快速对外提供能力,极大减少开发工作量和维护成本。
二、快速上手
步骤 1:安装组件
在 ASP.NET Core WebApi 项目中,通过 NuGet 安装:
Install-Package Panda.DynamicWebApi
步骤 2:创建服务类
创建一个类,实现 IDynamicWebApi 接口,并添加 [DynamicWebApi] 特性:
[DynamicWebApi]
public class AppleAppService : IDynamicWebApi
{
private static readonly Dictionary<int, string> Apples = new()
{
[1] = "Big Apple",
[2] = "Small Apple"
};
[HttpGet("{id:int}")]
public string Get(int id) => Apples.TryGetValue(id, out var apple) ? apple : "No Apple!";
public IEnumerable<string> Get() => Apples.Values;
public void Update(UpdateAppleDto dto)
{
if (Apples.ContainsKey(dto.Id))
Apples[dto.Id] = dto.Name;
}
[HttpDelete("{id:int}")]
public void Delete(int id) => Apples.Remove(id);
}
步骤 3:注册服务
在 Startup.cs 中添加注册逻辑:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDynamicWebApi(options =>
{
options.DefaultApiPrefix = "apis";
options.RemoveActionPostfixes.Clear();
options.GetRestFulActionName = name => name;
options.AddAssemblyOptions(typeof(Startup).Assembly, apiPreFix: "apis");
});
}
步骤 4:添加 Swagger(可选但推荐)
services.AddSwaggerGen();
在 Configure 方法中启用:
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"));
运行项目,访问 /swagger/index.html,你就能看到自动生成的 API 文档了。
三、更进一步的能力
1. 类和方法的识别规则
要自动生成 API:
- o 类必须实现 IDynamicWebApi
- o 并且类或其接口、抽象父类上必须标注 [DynamicWebApi] 特性
2. 动作命名和动词映射
根据方法名前缀,Panda.DynamicWebApi 会自动映射到合适的 HTTP 动词:
方法前缀动词Create/Add/PostPOSTGet/Find/QueryGETUpdate/PutPUTDelete/RemoveDELETE
例如:GetApple → GET /api/Apple
可以通过 ASP.NET Core 自带的 [HttpGet] 等特性手动覆盖。
四、自定义 WebAPI 注册方式
1. 自定义路由 + 控制器识别规则
你可以通过实现 ISelectController 和 IActionRouteFactory 接口来自定义 API 注册逻辑:
[AttributeUsage(AttributeTargets.Class)]
public class ServiceAttribute : Attribute
{
public string ServiceName { get; }
public ServiceAttribute(string name = "") => ServiceName = name;
}
自定义控制器选择器:
internal class ServiceLocalSelectController : ISelectController
{
public bool IsController(Type type) =>
type.IsPublic && type.GetCustomAttribute<ServiceAttribute>() != null;
}
自定义路由规则生成器:
internal class ServiceActionRouteFactory : IActionRouteFactory
{
public string CreateActionRouteModel(string area, string controller, ActionModel action)
{
var attr = action.ActionMethod.DeclaringType.GetCustomAttribute<ServiceAttribute>();
var serviceName = string.IsNullOrEmpty(attr?.ServiceName)
? controller.Replace("Service", "")
: attr.ServiceName.Replace("Service", "");
return #34;api/{serviceName}/{action.ActionName.Replace("Async", "")}";
}
}
2. 应用自定义规则
services.AddDynamicWebApiCore<ServiceLocalSelectController, ServiceActionRouteFactory>();
app.UseDynamicWebApi((sp, options) =>
{
options.AddAssemblyOptions(typeof(OtherService).Assembly);
});
这样,只要你的类标记了 [Service] 特性,就能自动变成一个 API 控制器,路由格式如 /api/ServiceName/Method。
五、配置说明
通过 DynamicWebApiOptions 可设置:
属性名默认值说明DefaultHttpVerbPOST默认 HTTP 动词DefaultApiPrefixapi路由前缀RemoveControllerPostfixesAppService, ApplicationService类名后缀去除规则RemoveActionPostfixesAsync方法名后缀去除规则FormBodyBindingIgnoredTypesIFormFile忽略表单类型参数
六、总结
Panda.DynamicWebApi 极大简化了 API 的开发流程,特别适合中后台系统或微服务架构下的场景:
- o 快速暴露服务为 API
- o 支持自定义路由、动词映射
- o 高度兼容 Swagger
- o 零侵入、低学习成本
项目地址:Panda.DynamicWebApi on NuGet
相关文章
- 网络爬虫:数据抓取的几种方法
- 计算机信息系统集成服务合同(中英文对照)
- 3D 渲染视频带你游览苹果"太空船"新总部园区 ...
- 微软发布SQL Server 2012 Service Pack 2
- 将数据从 MySQL 导出到 SQL Server
- Sugon and Hygon Announce Strategic Restructuring to Strengthen China's IT Industry Leadership
- 闪送如何授权并无需API集成连接其他系统
- 工业私有云如何安装PlantPAX
- (1图)美军:全球信息基础设施
- 隐形触手无处不在!智能家居、物联网:Java正在悄悄渗透你的生活