SyZero.DynamicWebApi 1.1.4-dev.1

This is a prerelease version of SyZero.DynamicWebApi.
There is a newer version of this package available.
See the version list below for details.
dotnet add package SyZero.DynamicWebApi --version 1.1.4-dev.1
                    
NuGet\Install-Package SyZero.DynamicWebApi -Version 1.1.4-dev.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SyZero.DynamicWebApi" Version="1.1.4-dev.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SyZero.DynamicWebApi" Version="1.1.4-dev.1" />
                    
Directory.Packages.props
<PackageReference Include="SyZero.DynamicWebApi" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add SyZero.DynamicWebApi --version 1.1.4-dev.1
                    
#r "nuget: SyZero.DynamicWebApi, 1.1.4-dev.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package SyZero.DynamicWebApi@1.1.4-dev.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=SyZero.DynamicWebApi&version=1.1.4-dev.1&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=SyZero.DynamicWebApi&version=1.1.4-dev.1&prerelease
                    
Install as a Cake Tool

SyZero.DynamicWebApi

动态 WebApi 生成框架,无需手动创建 Controller,自动从服务接口生成 RESTful API。

📦 安装

dotnet add package SyZero.DynamicWebApi

✨ 特性

  • 🚀 自动控制器生成 - 从 IDynamicApi 接口自动生成 WebApi 控制器
  • 🎯 零配置 - 只需标记 [DynamicApi] 即可生成 RESTful API
  • 高性能缓存 - 使用 ConcurrentDictionary 缓存反射结果
  • 🔧 灵活配置 - 支持自定义路由前缀、HTTP 动词映射等
  • 📖 Swagger 集成 - 自动生成 API 文档

🚀 快速开始

1. 定义数据模型

public class UserRequest
{
    public long Id { get; set; }
}

public class UserResponse
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

2. 定义服务接口

using SyZero.Application.Service;
using SyZero.Application.Attributes;

[DynamicApi]  // 标记在接口层,自动生成 WebApi
public interface IUserService : IApplicationService, IDynamicApi
{
    Task<UserResponse> GetUser(UserRequest request);
    
    Task<UserResponse> CreateUser(CreateUserRequest request);
    
    Task<UserResponse> UpdateUser(UpdateUserRequest request);
    
    Task DeleteUser(UserRequest request);
}

3. 实现服务

public class UserService : IUserService
{
    public Task<UserResponse> GetUser(UserRequest request)
    {
        return Task.FromResult(new UserResponse 
        { 
            Id = request.Id, 
            Name = "John Doe" 
        });
    }

    public Task<UserResponse> CreateUser(CreateUserRequest request)
    {
        // 实现创建逻辑
    }

    public Task<UserResponse> UpdateUser(UpdateUserRequest request)
    {
        // 实现更新逻辑
    }

    public Task DeleteUser(UserRequest request)
    {
        // 实现删除逻辑
    }
}

4. 配置服务

// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// 添加 Dynamic WebApi
builder.Services.AddDynamicWebApi(options =>
{
    options.DefaultApiPrefix = "api";
    options.DefaultAreaName = "v1";
    options.EnableLowerCaseRoutes = true;
});

var app = builder.Build();

app.MapControllers();

app.Run();

5. 自动生成的 API

上述配置会自动生成以下 API 端点:

HTTP 方法 路由 说明
GET /api/v1/user/get 获取用户
POST /api/v1/user/create 创建用户
PUT /api/v1/user/update 更新用户
DELETE /api/v1/user/delete 删除用户

📖 配置选项

DynamicWebApiOptions

属性 类型 默认值 说明
DefaultApiPrefix string "api" API 路由前缀
DefaultAreaName string null 默认区域名称
EnableLowerCaseRoutes bool false 启用小写路由
RemoveControllerPostfixes List<string> ["AppService", ...] 移除控制器后缀
RemoveActionPostfixes List<string> ["Async"] 移除 Action 后缀
HttpVerbMappings Dictionary<string, string> 默认映射 HTTP 动词映射

HTTP 动词自动映射

方法名前缀会自动映射到对应的 HTTP 动词:

方法前缀 HTTP 动词
Get, Query, Find, Fetch, Select GET
Post, Create, Add, Insert POST
Put, Update, Modify, Edit PUT
Delete, Remove DELETE
Patch PATCH

配置示例

builder.Services.AddDynamicWebApi(options =>
{
    options.DefaultApiPrefix = "api";
    options.DefaultAreaName = "v1";
    options.EnableLowerCaseRoutes = true;
    
    // 自定义 HTTP 动词映射
    options.HttpVerbMappings["Save"] = "POST";
    options.HttpVerbMappings["Batch"] = "POST";
});

配置文件配置

除了代码配置,也可以通过 appsettings.json 配置文件进行配置:

appsettings.json

{
  "DynamicWebApi": {
    "DefaultHttpVerb": "POST",
    "DefaultApiPrefix": "api",
    "DefaultAreaName": "v1",
    "EnableLowerCaseRoutes": true,
    "RemoveControllerPostfixes": ["AppService", "ApplicationService", "Service"],
    "RemoveActionPostfixes": ["Async"],
    "HttpVerbMappings": {
      "Get": "GET",
      "Query": "GET",
      "Find": "GET",
      "Create": "POST",
      "Add": "POST",
      "Update": "PUT",
      "Delete": "DELETE",
      "Save": "POST",
      "Batch": "POST"
    }
  }
}

Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// 方式一:从 IConfiguration 读取配置
builder.Services.AddDynamicWebApi(builder.Configuration);

// 方式二:从 IConfiguration 读取配置,并支持额外代码配置(代码配置会覆盖配置文件)
builder.Services.AddDynamicWebApi(builder.Configuration, options =>
{
    // 额外的代码配置
    options.AddHttpVerbMapping("Export", "GET");
});

// 方式三:指定自定义配置节名称
builder.Services.AddDynamicWebApi(builder.Configuration, "MyCustomSection");

// 方式四:从 AppConfig 读取配置(默认从 appsettings.json 的 "DynamicWebApi" 节点读取)
builder.Services.AddDynamicWebApi();

var app = builder.Build();

app.MapControllers();

app.Run();

🏷️ 特性标记

说明:标记了 [DynamicApi] 的接口会自动生成 WebApi 控制器。

NonWebApiServiceAttribute

排除某个 DynamicApi 服务不生成 WebApi:

[DynamicApi]
[NonWebApiService]  // 排除此服务不生成 WebApi
public interface IInternalService : IApplicationService, IDynamicApi
{
    // 此服务不会生成 WebApi,但可以生成 gRPC 服务
}

NonWebApiMethodAttribute

排除某个方法不生成 API 端点:

[DynamicApi]
public interface IUserService : IApplicationService, IDynamicApi
{
    Task<UserResponse> GetUser(UserRequest request);
    
    [NonWebApiMethod]  // 此方法不会生成 API 端点
    void InternalMethod();
}

NonDynamicApiAttribute

同时排除 WebApi 和 gRPC:

[DynamicApi]
[NonDynamicApi]  // 完全排除,不生成任何 API
public interface IPrivateService : IApplicationService, IDynamicApi
{
}

NonDynamicMethodAttribute

排除某个方法不生成任何 API(包括 gRPC):

[DynamicApi]
public interface IUserService : IApplicationService, IDynamicApi
{
    Task<UserResponse> GetUser(UserRequest request);
    
    [NonDynamicMethod]  // 不生成 WebApi 和 gRPC 方法
    void PrivateMethod();
}

🔗 与 DynamicGrpc 集成

同一服务同时支持 HTTP REST 和 gRPC:

[DynamicApi]  // 同时生成 HTTP API 和 gRPC 服务
public interface IUserService : IApplicationService, IDynamicApi
{
    Task<UserResponse> GetUser(UserRequest request);
}
// Program.cs
builder.Services.AddDynamicWebApi();  // HTTP API
builder.Services.AddDynamicGrpc();    // gRPC

var app = builder.Build();

app.MapControllers();          // HTTP 端点
app.MapDynamicGrpcServices();  // gRPC 端点

仅生成 WebApi(排除 gRPC)

[DynamicApi]
[NonGrpcService]  // 只生成 WebApi,不生成 gRPC
public interface IWebOnlyService : IApplicationService, IDynamicApi
{
}

仅生成 gRPC(排除 WebApi)

[DynamicApi]
[NonWebApiService]  // 只生成 gRPC,不生成 WebApi
public interface IGrpcOnlyService : IApplicationService, IDynamicApi
{
}

📁 项目结构

SyZero.DynamicWebApi/
├── Attributes/
│   └── WebApiAttributes.cs        # WebApi 特性标记
├── Helpers/
│   ├── ReflectionHelper.cs        # 反射帮助类
│   ├── TypeHelper.cs              # 类型帮助类
│   └── ExtensionMethods.cs        # 扩展方法
├── AppConsts.cs                   # 常量定义
├── AssemblyDynamicWebApiOptions.cs # 程序集配置
├── DynamicWebApiControllerFeatureProvider.cs # 控制器特性提供程序
├── DynamicWebApiConvention.cs     # MVC 约定
├── DynamicWebApiOptions.cs        # 配置选项(支持代码配置和配置文件绑定)
└── DynamicWebApiServiceExtensions.cs # 服务扩展方法

📚 Swagger 集成

Dynamic WebApi 自动支持 Swagger 文档生成:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDynamicWebApi();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.MapControllers();

📄 许可证

MIT License - 详见 LICENSE

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net9.0

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.5-dev.1 33 1/29/2026
1.1.4 92 1/2/2026
1.1.4-dev.2 46 1/2/2026
1.1.4-dev.1 44 12/30/2025
1.1.3 96 12/30/2025
1.1.3-dev.6 46 12/30/2025
1.1.3-dev.3 104 1/19/2024
1.1.3-dev.2 164 11/3/2023
1.1.3-dev.1 193 3/21/2023
1.1.2 373 3/15/2023
1.1.2-dev.108.29344 182 3/15/2023
1.1.2-dev.108.28054 195 3/15/2023
1.1.2-dev.108.27487 181 3/15/2023
1.1.1 316 3/15/2023
1.1.1-dev.108.14980 180 3/15/2023
1.1.1-dev.108.13289 176 3/15/2023
1.1.1-dev.107.27144 180 3/14/2023
1.1.0 308 3/14/2023
1.1.0-workflow-dev.107.22552 175 3/14/2023
1.1.0-workflow-dev.107.21746 179 3/14/2023
1.1.0-workflow-dev.107.21506 176 3/14/2023
1.1.0-workflow-dev.107.20979 181 3/14/2023
1.1.0-dev.107.26364 180 3/14/2023
1.1.0-dev.107.24396 186 3/14/2023
1.1.0-dev.107.22787 186 3/14/2023
1.0.6 576 3/5/2022
1.0.1 884 2/20/2020