Smart.Api
5.1.0
See the version list below for details.
dotnet new install Smart.Api::5.1.0
Smart.Api
基于 ASP.NET Core 10 平台的 WebAPI 快速开发框架,采用领域驱动设计(DDD)架构,集成服务自动注册、模块化认证授权、生产级日志、审计追踪等企业级特性。
目录
核心特性
基础架构
| 特性 | 描述 |
|---|---|
| DDD架构 | 四层架构设计,清晰的职责分离 |
| 服务自动注册 | 基于 Smart.Inject 的自动依赖注入,支持生命周期配置 |
| 跨平台支持 | 兼容 Windows / Linux / macOS |
| 容器化部署 | 内置 Dockerfile,支持 Docker 容器化部署 |
| 编码扩展 | 内置 GBK/GB2312 中文编码支持 |
安全特性
| 特性 | 描述 |
|---|---|
| JWT认证 | 完整的 JWT Token 生成、验证、刷新机制 |
| 角色授权 | 基于角色的层级权限控制(RBAC) |
| 密码管理 | 集成 ASP.NET Core Identity,支持密码重置、邮箱验证 |
| 审计日志 | 自动记录用户操作日志,支持异步入库 |
| 重放攻击防护 | 内置请求重放攻击防护中间件 |
开发体验
| 特性 | 描述 |
|---|---|
| Swagger文档 | 带 JWT 认证支持的交互式 API 文档 |
| 健康检查 | 内置 /health 和 /health/detail 端点 |
| 实时通信 | SignalR Hub 示例,支持认证/匿名连接 |
| 数据库迁移 | EF Core 自动数据库迁移 |
| 统一响应格式 | 标准化 API 响应格式 Result<T> |
架构设计
┌─────────────────────────────────────────────────────────────────┐
│ Smart.Api (宿主层) │
│ 程序入口、中间件管道、控制器、SignalR Hub、启动配置 │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Smart.Api.Application (应用层) │
│ 应用服务编排、DTO、用例协调、后台服务 │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Smart.Api.Domain (领域层) │
│ 实体、值对象、领域服务、仓储接口、领域事件、业务规则 │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Smart.Api.Infrastructure (基础设施层) │
│ 数据访问、仓储实现、缓存、消息队列、外部服务、配置管理 │
└─────────────────────────────────────────────────────────────────┘
层级职责
| 层级 | 项目 | 职责 |
|---|---|---|
| 宿主层 | Smart.Api |
应用程序入口,负责启动配置、中间件管道、HTTP 请求处理 |
| 应用层 | Smart.Api.Application |
协调领域对象完成用例,定义应用服务接口和 DTO |
| 领域层 | Smart.Api.Domain |
核心业务逻辑,包含实体、值对象、领域服务,无外部依赖 |
| 基础设施层 | Smart.Api.Infrastructure |
技术实现,提供数据持久化、外部服务集成等基础设施 |
技术栈
| 类别 | 技术 | 版本 |
|---|---|---|
| 运行时 | .NET | 10.0 |
| Web框架 | ASP.NET Core | 10.0 |
| ORM | Entity Framework Core | 10.0 |
| 数据库 | PostgreSQL | 14+ |
| 认证 | JWT Bearer | 10.0 |
| 日志 | NLog | - |
| 验证 | FluentValidation | 12.1 |
| 实时通信 | SignalR | - |
| API文档 | Swagger/OpenAPI | 10.1 |
| 依赖注入 | Smart.Inject | 5.2 |
| 邮件服务 | Smart.MailKit | 4.2 |
| 消息队列 | Smart.RabbitMQ | 1.0 |
| 缓存 | Smart.StackRedis | - |
快速开始
环境要求
- .NET SDK 10.0+
- PostgreSQL 14+(或其他兼容数据库)
- Visual Studio 2022 / JetBrains Rider / VS Code
安装模板
dotnet new install Smart.Api
创建项目
dotnet new smart.api -n MyProject
cd MyProject
配置数据库连接
编辑 appsettings.Development.json:
{
"ConnectionStrings": {
"PgSQL": "Host=localhost;Port=5432;Database=mydb;Username=postgres;Password=your_password"
}
}
配置 JWT
{
"JwtOption": {
"Issuer": "your-issuer",
"Audience": "your-audience",
"SecurityKey": "your-secret-key-at-least-32-characters-long",
"AccessTokenExpires": 900,
"RefreshTokenExpires": 604800
}
}
运行项目
dotnet run
访问 http://localhost:5000/swagger 查看 API 文档。
项目结构
Smart.Api/
├── .template.config/
│ └── template.json # NuGet 模板配置
├── Smart.Api/ # 宿主层
│ ├── Controllers/ # API 控制器
│ │ ├── Account/ # 账户相关(登录、注册、密码管理等)
│ │ └── File/ # 文件上传下载
│ ├── Extensions/ # 服务扩展方法
│ │ ├── AuthExtensions.cs # JWT 认证扩展
│ │ ├── CorsExtensions.cs # CORS 策略扩展
│ │ └── HealthCheckExtensions.cs
│ ├── Filters/ # MVC 过滤器
│ │ ├── AuditLogFilter.cs # 审计日志过滤器
│ │ └── ExceptionFilter.cs # 异常处理过滤器
│ ├── Hubs/ # SignalR Hub
│ ├── Middlewares/ # 自定义中间件
│ ├── Swagger/ # Swagger 配置
│ ├── Program.cs # 程序入口
│ ├── ServiceConfigure.cs # 服务配置
│ ├── NLog.config # 日志配置
│ └── appsettings.*.json # 配置文件
├── Smart.Api.Application/ # 应用层
│ └── ServiceConfigure.cs
├── Smart.Api.Domain/ # 领域层
│ ├── Attributes/ # 领域特性
│ ├── Authorizations/ # 授权相关
│ │ ├── AppPolicy.cs # 授权策略
│ │ ├── AppRole.cs # 角色定义
│ │ └── UserClaims.cs # 用户声明
│ ├── Data/ # 领域实体
│ │ ├── AppIdentityUser.cs # 用户实体
│ │ ├── AppIdentityRole.cs # 角色实体
│ │ └── ApiAuditLog.cs # 审计日志实体
│ ├── Options/ # 配置选项
│ ├── Result.cs # 统一响应格式
│ └── ResponseCode.cs # 响应代码枚举
├── Smart.Api.Infrastructure/ # 基础设施层
│ ├── Authorizations/ # 授权处理器
│ ├── BackgroundServices/ # 后台服务
│ │ ├── AuditLogHostedService.cs
│ │ └── MailNotificationHostedService.cs
│ ├── Extensions/ # 扩展方法
│ ├── Identity/ # 数据库上下文
│ │ ├── AppDbContext.cs
│ │ └── Config/ # 实体配置
│ ├── Migrations/ # 数据库迁移
│ └── Services/ # 应用服务实现
│ ├── Account/ # 账户服务
│ ├── Audit/ # 审计服务
│ ├── File/ # 文件服务
│ └── Jwt/ # JWT 服务
├── Directory.Build.props # 构建属性
├── Smart.Api.slnx # 解决方案文件
└── Smart.Api.nuspec # NuGet 包规范
核心模块
统一响应格式
所有 API 响应采用统一的 Result<T> 格式:
public class Result
{
public int Code { get; init; } // 响应代码(0=成功)
public string Message { get; init; } // 响应消息
public long Timestamp { get; init; } // UTC 时间戳
}
public class Result<T> : Result
{
public T? Data { get; init; } // 响应数据
}
使用示例:
[HttpGet("{id}")]
public async Task<Result<UserDto>> GetUser(int id)
{
var user = await _userService.GetByIdAsync(id);
return Result<UserDto>.Ok(user);
}
服务自动注册
通过 Smart.Inject 实现服务自动扫描注册:
[Service(ServiceLifetime.Scoped, InjectScheme.OnlySelf)]
public class UserService
{
}
[Service(ServiceLifetime.Singleton, InjectScheme.ImplementInterfaces)]
public class CacheService : ICacheService
{
}
注册模式:
| 模式 | 说明 |
|---|---|
OnlySelf |
仅注册自身类型 |
ImplementInterfaces |
注册所有实现的接口 |
SelfAndInterfaces |
同时注册自身和接口 |
角色授权
内置基于层级的角色授权系统:
public enum AppRole : byte
{
Employee = 1, // 员工
Tenant = 2, // 租户
Admin = 3, // 系统管理员
SuperAdmin = 4 // 超级管理员
}
使用示例:
[MinRoleAuthorize(AppRole.Admin)]
[HttpGet("admin/data")]
public async Task<Result> GetAdminData()
{
}
JWT 认证
完整的 JWT Token 管理服务:
public class SmartJwtService
{
Task<string> GenerateAccessTokenAsync(ClaimsPrincipal user);
Task<string> GenerateRefreshTokenAsync();
ClaimsPrincipal? ValidateToken(string token);
}
审计日志
通过 AuditLogFilter 自动记录用户操作:
[AuditLog("用户登录")]
[HttpPost("login")]
public async Task<Result<LoginResult>> Login(LoginCredential credential)
{
}
健康检查
内置两个健康检查端点:
| 端点 | 用途 | 说明 |
|---|---|---|
/health |
负载均衡探测 | 返回 200 OK,不执行具体检查 |
/health/detail |
监控系统 | 返回详细健康状态,包含各组件检查结果 |
配置说明
JWT 配置
{
"JwtOption": {
"Issuer": "your-issuer",
"Audience": "your-audience",
"SecurityKey": "your-secret-key-at-least-32-characters-long",
"AccessTokenExpires": 900,
"RefreshTokenExpires": 604800
}
}
| 参数 | 说明 | 默认值 |
|---|---|---|
Issuer |
Token 签发者 | - |
Audience |
Token 接收者 | - |
SecurityKey |
签名密钥(最少32字符) | - |
AccessTokenExpires |
访问令牌有效期(秒) | 900 (15分钟) |
RefreshTokenExpires |
刷新令牌有效期(秒) | 604800 (7天) |
CORS 配置
{
"CorsOption": {
"Origins": ["https://example.com", "https://admin.example.com"],
"AllowCredentials": true
}
}
身份认证配置
{
"IdentityOption": {
"RequireDigit": true,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireNonAlphanumeric": false,
"RequiredLength": 8
}
}
部署指南
Docker 部署
docker build -t smart-api:latest .
docker run -d -p 8080:80 smart-api:latest
框架依赖部署
必须使用「依赖框架」部署模式:
dotnet publish -c Release --self-contained false -f net10.0
| 部署模式 | 适用场景 | 本模板要求 |
|---|---|---|
| 依赖框架 | 目标机器已安装 .NET 运行时 | ✅ 强制使用 |
| 独立部署 | 无运行时环境 | ❌ 不支持 |
推荐搭配 .NET 运行时安装脚本 部署
环境变量
| 变量名 | 说明 |
|---|---|
ASPNETCORE_ENVIRONMENT |
运行环境 |
ConnectionStrings__PgSQL |
数据库连接字符串 |
开发指南
添加新的 API 控制器
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
[HttpGet]
public async Task<Result<List<ProductDto>>> GetAll()
{
}
}
添加新的应用服务
[Service(ServiceLifetime.Scoped, InjectScheme.OnlySelf)]
public class ProductService
{
private readonly AppDbContext _context;
public ProductService(AppDbContext context)
{
_context = context;
}
}
添加数据库迁移
dotnet ef migrations add AddProductTable --project Smart.Api.Infrastructure --startup-project Smart.Api
dotnet ef database update --project Smart.Api.Infrastructure --startup-project Smart.Api
日志配置
日志配置位于 NLog.config,默认配置:
| 日志类型 | 文件路径 | 保留天数 | 单文件大小限制 |
|---|---|---|---|
| 全量日志 | Logs/allLog-{date}.log |
30天 | 50MB |
| 错误日志 | Logs/errLog-{date}.log |
60天 | 50MB |
贡献指南
- Fork 本仓库
- 创建特性分支 (
git checkout -b feature/AmazingFeature) - 提交更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 提交 Pull Request
许可证
本项目采用 MIT 许可证。
Developed by zenglei
Smart.Api
A rapid WebAPI development framework based on ASP.NET Core 10, featuring Domain-Driven Design (DDD) architecture with enterprise-grade features including automatic service registration, modular authentication, production-grade logging, and audit tracking.
Table of Contents
- Core Features
- Architecture Design
- Technology Stack
- Quick Start
- Project Structure
- Core Modules
- Configuration
- Deployment Guide
- Development Guide
- Contributing
Core Features
Infrastructure
| Feature | Description |
|---|---|
| DDD Architecture | Four-layer architecture design with clear separation of concerns |
| Auto Service Registration | Automatic dependency injection based on Smart.Inject with lifecycle configuration |
| Cross-Platform | Compatible with Windows / Linux / macOS |
| Containerization | Built-in Dockerfile for Docker container deployment |
| Encoding Extension | Built-in GBK/GB2312 Chinese encoding support |
Security Features
| Feature | Description |
|---|---|
| JWT Authentication | Complete JWT Token generation, validation, and refresh mechanism |
| Role Authorization | Role-based hierarchical permission control (RBAC) |
| Password Management | Integrated ASP.NET Core Identity with password reset and email verification |
| Audit Logging | Automatic user operation logging with async persistence |
| Replay Attack Protection | Built-in request replay attack protection middleware |
Developer Experience
| Feature | Description |
|---|---|
| Swagger Documentation | Interactive API documentation with JWT authentication support |
| Health Checks | Built-in /health and /health/detail endpoints |
| Real-time Communication | SignalR Hub examples with authenticated/anonymous connections |
| Database Migration | EF Core automatic database migration |
| Unified Response Format | Standardized API response format Result<T> |
Architecture Design
┌─────────────────────────────────────────────────────────────────┐
│ Smart.Api (Host Layer) │
│ Application entry, middleware pipeline, controllers, SignalR │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Smart.Api.Application (Application Layer) │
│ Application services, DTOs, use case orchestration │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Smart.Api.Domain (Domain Layer) │
│ Entities, value objects, domain services, repository interfaces│
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Smart.Api.Infrastructure (Infrastructure Layer) │
│ Data access, repository implementations, external services │
└─────────────────────────────────────────────────────────────────┘
Layer Responsibilities
| Layer | Project | Responsibility |
|---|---|---|
| Host Layer | Smart.Api |
Application entry point, startup configuration, middleware pipeline |
| Application Layer | Smart.Api.Application |
Coordinates domain objects for use cases, defines service interfaces and DTOs |
| Domain Layer | Smart.Api.Domain |
Core business logic, entities, value objects, domain services, no external dependencies |
| Infrastructure Layer | Smart.Api.Infrastructure |
Technical implementations, data persistence, external service integration |
Technology Stack
| Category | Technology | Version |
|---|---|---|
| Runtime | .NET | 10.0 |
| Web Framework | ASP.NET Core | 10.0 |
| ORM | Entity Framework Core | 10.0 |
| Database | PostgreSQL | 14+ |
| Authentication | JWT Bearer | 10.0 |
| Logging | NLog | - |
| Validation | FluentValidation | 12.1 |
| Real-time | SignalR | - |
| API Documentation | Swagger/OpenAPI | 10.1 |
| Dependency Injection | Smart.Inject | 5.2 |
| Email Service | Smart.MailKit | 4.2 |
| Message Queue | Smart.RabbitMQ | 1.0 |
| Caching | Smart.StackRedis | - |
Quick Start
Requirements
- .NET SDK 10.0+
- PostgreSQL 14+ (or compatible database)
- Visual Studio 2022 / JetBrains Rider / VS Code
Install Template
dotnet new install Smart.Api
Create Project
dotnet new smart.api -n MyProject
cd MyProject
Configure Database Connection
Edit appsettings.Development.json:
{
"ConnectionStrings": {
"PgSQL": "Host=localhost;Port=5432;Database=mydb;Username=postgres;Password=your_password"
}
}
Configure JWT
{
"JwtOption": {
"Issuer": "your-issuer",
"Audience": "your-audience",
"SecurityKey": "your-secret-key-at-least-32-characters-long",
"AccessTokenExpires": 900,
"RefreshTokenExpires": 604800
}
}
Run Project
dotnet run
Visit http://localhost:5000/swagger to view API documentation.
Project Structure
Smart.Api/
├── .template.config/
│ └── template.json # NuGet template configuration
├── Smart.Api/ # Host Layer
│ ├── Controllers/ # API Controllers
│ │ ├── Account/ # Account (login, register, password management)
│ │ └── File/ # File upload/download
│ ├── Extensions/ # Service extension methods
│ ├── Filters/ # MVC filters
│ ├── Hubs/ # SignalR Hubs
│ ├── Middlewares/ # Custom middleware
│ ├── Swagger/ # Swagger configuration
│ ├── Program.cs # Application entry
│ ├── ServiceConfigure.cs # Service configuration
│ ├── NLog.config # Logging configuration
│ └── appsettings.*.json # Configuration files
├── Smart.Api.Application/ # Application Layer
├── Smart.Api.Domain/ # Domain Layer
│ ├── Attributes/ # Domain attributes
│ ├── Authorizations/ # Authorization definitions
│ ├── Data/ # Domain entities
│ ├── Options/ # Configuration options
│ ├── Result.cs # Unified response format
│ └── ResponseCode.cs # Response code enumeration
├── Smart.Api.Infrastructure/ # Infrastructure Layer
│ ├── Authorizations/ # Authorization handlers
│ ├── BackgroundServices/ # Background services
│ ├── Extensions/ # Extension methods
│ ├── Identity/ # Database context
│ ├── Migrations/ # Database migrations
│ └── Services/ # Service implementations
├── Directory.Build.props # Build properties
├── Smart.Api.slnx # Solution file
└── Smart.Api.nuspec # NuGet package specification
Core Modules
Unified Response Format
All API responses use a unified Result<T> format:
public class Result
{
public int Code { get; init; } // Response code (0=success)
public string Message { get; init; } // Response message
public long Timestamp { get; init; } // UTC timestamp
}
public class Result<T> : Result
{
public T? Data { get; init; } // Response data
}
Usage Example:
[HttpGet("{id}")]
public async Task<Result<UserDto>> GetUser(int id)
{
var user = await _userService.GetByIdAsync(id);
return Result<UserDto>.Ok(user);
}
Auto Service Registration
Automatic service scanning and registration via Smart.Inject:
[Service(ServiceLifetime.Scoped, InjectScheme.OnlySelf)]
public class UserService
{
}
[Service(ServiceLifetime.Singleton, InjectScheme.ImplementInterfaces)]
public class CacheService : ICacheService
{
}
Registration Schemes:
| Scheme | Description |
|---|---|
OnlySelf |
Register only the type itself |
ImplementInterfaces |
Register all implemented interfaces |
SelfAndInterfaces |
Register both self and interfaces |
Role Authorization
Built-in hierarchical role-based authorization:
public enum AppRole : byte
{
Employee = 1, // Employee
Tenant = 2, // Tenant
Admin = 3, // System Administrator
SuperAdmin = 4 // Super Administrator
}
Usage Example:
[MinRoleAuthorize(AppRole.Admin)]
[HttpGet("admin/data")]
public async Task<Result> GetAdminData()
{
}
JWT Authentication
Complete JWT Token management service:
public class SmartJwtService
{
Task<string> GenerateAccessTokenAsync(ClaimsPrincipal user);
Task<string> GenerateRefreshTokenAsync();
ClaimsPrincipal? ValidateToken(string token);
}
Audit Logging
Automatic user operation logging via AuditLogFilter:
[AuditLog("User Login")]
[HttpPost("login")]
public async Task<Result<LoginResult>> Login(LoginCredential credential)
{
}
Health Checks
Built-in health check endpoints:
| Endpoint | Purpose | Description |
|---|---|---|
/health |
Load balancer probing | Returns 200 OK without specific checks |
/health/detail |
Monitoring system | Returns detailed health status with component results |
Configuration
JWT Configuration
{
"JwtOption": {
"Issuer": "your-issuer",
"Audience": "your-audience",
"SecurityKey": "your-secret-key-at-least-32-characters-long",
"AccessTokenExpires": 900,
"RefreshTokenExpires": 604800
}
}
| Parameter | Description | Default |
|---|---|---|
Issuer |
Token issuer | - |
Audience |
Token audience | - |
SecurityKey |
Signing key (min 32 characters) | - |
AccessTokenExpires |
Access token expiry (seconds) | 900 (15 minutes) |
RefreshTokenExpires |
Refresh token expiry (seconds) | 604800 (7 days) |
CORS Configuration
{
"CorsOption": {
"Origins": ["https://example.com", "https://admin.example.com"],
"AllowCredentials": true
}
}
Identity Configuration
{
"IdentityOption": {
"RequireDigit": true,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireNonAlphanumeric": false,
"RequiredLength": 8
}
}
Deployment Guide
Docker Deployment
docker build -t smart-api:latest .
docker run -d -p 8080:80 smart-api:latest
Framework-Dependent Deployment
Must use framework-dependent deployment mode:
dotnet publish -c Release --self-contained false -f net10.0
| Deployment Mode | Use Case | Template Requirement |
|---|---|---|
| Framework-dependent | Target machine has .NET runtime | ✅ Required |
| Self-contained | No runtime environment | ❌ Not supported |
Recommended to use .NET runtime install scripts for deployment
Environment Variables
| Variable | Description |
|---|---|
ASPNETCORE_ENVIRONMENT |
Runtime environment |
ConnectionStrings__PgSQL |
Database connection string |
Development Guide
Add New API Controller
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
[HttpGet]
public async Task<Result<List<ProductDto>>> GetAll()
{
}
}
Add New Application Service
[Service(ServiceLifetime.Scoped, InjectScheme.OnlySelf)]
public class ProductService
{
private readonly AppDbContext _context;
public ProductService(AppDbContext context)
{
_context = context;
}
}
Add Database Migration
dotnet ef migrations add AddProductTable --project Smart.Api.Infrastructure --startup-project Smart.Api
dotnet ef database update --project Smart.Api.Infrastructure --startup-project Smart.Api
Logging Configuration
Logging configuration is located in NLog.config with default settings:
| Log Type | File Path | Retention | Size Limit |
|---|---|---|---|
| All logs | Logs/allLog-{date}.log |
30 days | 50MB |
| Error logs | Logs/errLog-{date}.log |
60 days | 50MB |
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
License
This project is licensed under the MIT License.
Developed by zenglei
This package has no dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.