No description
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-05-19 18:29:59 +08:00
.vscode Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
Controllers Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
Extensions Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
Models Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
Properties Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
Services Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
Tests/Controllers Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
.gitignore Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
appsettings.Development.json Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
appsettings.json Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
LineServer.csproj Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
LineServer.csproj.lscache Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
LineServer.sln Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
README.md Initial commit: MES line server API 2026-05-19 18:29:59 +08:00
ServerLauncher.cs Initial commit: MES line server API 2026-05-19 18:29:59 +08:00

LineServer - 产线后台服务

项目简介

LineServer 是一个基于 ASP.NET Core 6 的产线设备管理和监控 Web API 服务。该项目与 LineBackendServer 配合工作,提供设备信息查询、状态管理和实时产能监控功能。

技术栈

  • 框架: ASP.NET Core 6
  • 运行时: .NET 6
  • 依赖注入: Microsoft.Extensions.DependencyInjection
  • 日志: Microsoft.Extensions.Logging
  • API 文档: Swagger/OpenAPI

项目结构

LineServer/
├── Controllers/              # 控制器层
│   ├── BaseApiController.cs # 基础控制器
│   └── EquipController.cs   # 设备管理控制器
├── Services/                 # 业务逻辑层
│   ├── IEquipService.cs     # 设备服务接口
│   └── EquipServiceAdapter.cs # 服务实现(适配器模式)
├── Models/                   # 数据模型
│   ├── Result.cs            # 通用响应模型
│   ├── PagedResult.cs       # 分页响应模型
│   └── PagedList.cs         # 分页列表数据
├── Extensions/               # 扩展类
│   ├── PaginationExtensions.cs # 分页扩展
│   └── ServiceExtensions.cs  # DI 注册扩展
├── Tests/                    # 单元测试
├── Program.cs               # 应用入口点
├── ServerLauncher.cs        # 服务启动器和配置
└── Startup.cs               # Startup 类

快速开始

编译项目

cd LineServer
dotnet build

运行服务

dotnet run

服务将在 https://localhost:5001 启动。

访问 API 文档

启动后,可以访问 Swagger UI:

https://localhost:5001/swagger

API 端点

设备查询

1. 获取所有设备

GET /api/equip/SearchAllInfoByLineId?lineId=1

响应:

[
  {
    "id": 1,
    "equipCode": "EQ001",
    "equipName": "设备1",
    ...
  }
]

2. 根据设备ID查询

GET /api/equip/SearchInfoById?equipId=1

3. 根据设备代号查询

GET /api/equip/SearchInfoByEquipCode?equipCode=EQ001

4. 查询设备状态

GET /api/equip/SearchEquipmentStatusById?equipId=1

5. 查询实时产能

GET /api/equip/SearchRealTimeCapacity?equipId=1&time=2024-01-01T10:00:00

设备管理

1. 新增设备

POST /api/equip/InsertInfo
Content-Type: application/json

{
  "equipCode": "EQ002",
  "equipName": "新设备",
  ...
}

2. 插入设备结果

POST /api/equip/InsertResult
Content-Type: application/json

{
  "equipId": 1,
  "resultData": "...",
  ...
}

3. 更新设备状态

POST /api/equip/UpdateStatus
Content-Type: application/json

{
  "equipId": 1,
  "status": "Running",
  ...
}

健康检查

GET /api/equip

响应:

{
  "isSuccess": true,
  "value": "通讯成功",
  "error": null,
  "statusCode": 200
}

配置说明

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  },
  "AllowedHosts": "*"
}

数据库配置

数据库使用 SQLite,默认路径:

{应用根目录}/LineBackend.sqlite

可以通过修改 ServerLauncher.cs 中的 InitializeDatabaseAsync 方法更改。

依赖注入配置

所有服务都通过 DI 容器管理:

// 在 ServerLauncher.cs 或 Startup.cs 中
services.AddScoped<IEquipService, EquipServiceAdapter>();

或使用扩展方法:

services.AddApplicationServices();

日志使用

基本用法

_logger.LogInformation("设备查询: {EquipId}", equipId);
_logger.LogWarning("无效的设备ID: {EquipId}", equipId);
_logger.LogError(ex, "操作 '{Operation}' 失败", operationName);

日志级别

  • Information: 一般信息
  • Warning: 警告信息(如参数错误)
  • Error: 错误信息(如异常)
  • Debug: 调试信息

异步编程

所有 API 都支持异步操作和取消令牌:

public async Task<IActionResult> SearchEquipmentInfoByIdAsync(
    int equipId,
    CancellationToken cancellationToken = default)
{
    var result = await _equipService.SearchEquipmentInfoByIdAsync(equipId, cancellationToken);
    return HandleResult(Result<EquipInfoDTO>.Success(result));
}

错误处理

响应格式

成功响应 (200 OK):

{
  "id": 1,
  "equipCode": "EQ001",
  "equipName": "设备1"
}

失败响应 (400 Bad Request):

{
  "error": "设备ID不合法"
}

服务器错误 (500 Internal Server Error):

{
  "error": "An internal error occurred",
  "details": "Exception message"
}

单元测试

项目包含示例单元测试,使用 xUnit 和 Moq:

# 运行所有测试
dotnet test

# 运行特定测试
dotnet test --filter "EquipControllerTests"

# 生成覆盖率报告
dotnet-coverage collect -f cobertura -o coverage.cobertura.xml dotnet test

最佳实践

✅ 应该做

  1. 参数验证

    if (equipId <= 0)
        return HandleResult(Result<T>.Failure("设备ID不合法", 400));
    
  2. 异步操作

    var result = await _equipService.SearchEquipmentInfoByIdAsync(equipId, cancellationToken);
    
  3. 日志记录

    _logger.LogWarning("Invalid equipId: {EquipId}", equipId);
    
  4. 使用 IActionResult

    public async Task<IActionResult> MyMethodAsync() { ... }
    

❌ 不应该做

  1. 直接 new 服务

    // ❌ 不要这样做
    var service = new EquipService();
    
    // ✅ 应该通过构造函数注入
    public EquipController(IEquipService equipService, ILogger<EquipController> logger)
    
  2. 忽视取消令牌

    // ❌ 不要这样做
    await Task.Delay(5000);
    
    // ✅ 应该这样做
    await Task.Delay(5000, cancellationToken);
    
  3. 吞掉异常

    // ❌ 不要这样做
    try { ... } catch { }
    
    // ✅ 应该记录并返回正确的错误响应
    catch (Exception ex) {
        _logger.LogError(ex, "Operation failed");
        return HandleException(ex, nameof(MethodName));
    }
    

性能优化

推荐配置

  1. 启用响应压缩

    services.AddResponseCompression();
    app.UseResponseCompression();
    
  2. 使用内存缓存

    services.AddMemoryCache();
    
  3. 使用连接池

    • 数据库连接复用
    • HTTP 连接复用

安全性

推荐加固

  1. 启用 HTTPS

    • 强制 HTTPS 重定向
    • 设置 HSTS 头
  2. 输入验证

    • 验证所有用户输入
    • 使用 FluentValidation
  3. 认证和授权

    • 添加 JWT 认证
    • 实现基于角色的访问控制 (RBAC)
  4. API 安全

    • 启用 CORS
    • 实现速率限制
    • 添加 API 密钥验证

监控和诊断

健康检查

[HttpGet("health")]
public IActionResult Health()
{
    return Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
}

应用洞察 (Application Insights)

集成 Application Insights 进行遥测和监控:

services.AddApplicationInsightsTelemetry();

故障排除

问题:编译错误 CS0117

原因: 使用了 .NET 8+ 才有的方法(如 ThrowIfLessThanOrEqual)

解决: 使用 .NET 6 兼容的方式:

if (equipId <= 0)
    throw new ArgumentException("Invalid", nameof(equipId));

问题:数据库连接失败

检查:

  1. SQLite 文件路径是否正确
  2. 文件夹是否有写入权限
  3. 数据库文件是否被锁定

问题:Swagger 不显示

检查:

  1. XML 文档注释文件是否存在
  2. 是否启用了 IncludeXmlComments
  3. 路由配置是否正确

贡献指南

  1. Fork 项目
  2. 创建功能分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request

许可证

未指定

联系方式

相关资源


版本: 1.0.0
最后更新: 2024