Healnet.Core 4.0.15

dotnet add package Healnet.Core --version 4.0.15
                    
NuGet\Install-Package Healnet.Core -Version 4.0.15
                    
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="Healnet.Core" Version="4.0.15" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Healnet.Core" Version="4.0.15" />
                    
Directory.Packages.props
<PackageReference Include="Healnet.Core" />
                    
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 Healnet.Core --version 4.0.15
                    
#r "nuget: Healnet.Core, 4.0.15"
                    
#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 Healnet.Core@4.0.15
                    
#: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=Healnet.Core&version=4.0.15
                    
Install as a Cake Addin
#tool nuget:?package=Healnet.Core&version=4.0.15
                    
Install as a Cake Tool

Healnet.Core 核心契约层

版本: v4.0.14 | TFM: net10.0 | 依赖: Healnet.Common | NuGet: Healnet.Core 4.0.14

概述

Healnet.Core 是 Healnet 微服务框架的核心契约层,提供领域驱动设计(DDD)基础设施、统一异常体系、仓储/缓存/日志抽象、API 响应格式、微服务通用能力抽象,以及 AI 能力的抽象契约。它只定义抽象契约与 POCO,不携带任何具体技术 SDK 依赖——这是"依赖倒置(DIP)"的关键:上层 Infrastructure 实现这些契约,而契约本身保持稳定、可被任意宿主复用。

⭐ AI 能力已彻底 DIP:所有 AI 抽象接口、选项 POCO、上下文模型、记忆契约/实体已上移至本层(Healnet.Core.AI / Healnet.Core.AI.Memory)。Core 的 csproj 不引用 Microsoft.Extensions.AI / Semantic Kernel / Agent Framework——这些契约是纯接口 + POCO,与具体 AI 框架完全解耦。具体实现(如 UnifiedAIService)在 Healnet.Infrastructure.AI。

⚠️ 重要说明:

  1. Core 不提供 AddCore() 之类的 DI 注册方法。它仅包含契约与抽象;具体注册在 Healnet.Infrastructure 或宿主项目完成。
  2. Core 不含 MediatR / CQRS(ICommand/IQuery/IMediator 并非库 API,仅旧文档示例残留)。
  3. 旧文档出现的 Enumeration、Filtering 类型不存在于源码。
  4. 关于 ReleaseNotes 的模块归属:Core 的 PackageReleaseNotes 在 3.0.1 条目中提及“新增 ApiKeyAuthenticationHandler”与“新增 GrpcClientBase 泛型基类”,但经核对源码,这两个类型实际位于 Healnet.Infrastructure(Infrastructure.Authentication.ApiKeyAuthenticationHandler 与 Infrastructure.gRPC.GrpcClientBase),属于实现层而非 Core 类型。Core 仅定义认证抽象(ITokenService/JwtOptions)与 Consul 抽象(IConsulService/ConsulOptions)。下方版本历史忠实引用 csproj ReleaseNotes 的变更描述,请以类型实际所在程序集为准。

核心特性

  • ✅ DDD 实体 - Entity<TKey> / AggregateRoot<TKey> / ValueObject / AuditableEntity / SoftDeleteEntity / DomainEvent
  • ✅ 统一异常 - 7 种 HTTP 业务异常 + 协议异常(带固定 ErrorCode)
  • ✅ 仓储模式 - IRepository<T,TKey> / IReadOnlyRepository<T,TKey> 泛型接口
  • ✅ 工作单元 - IUnitOfWork(事务抽象)
  • ✅ 服务基类 - BaseService / CrudService<TEntity,TRequest,TResponse,TKey>
  • ✅ API 响应 - ApiResponse / ApiResponse<T> / PagedResponse<T>
  • ✅ 消息队列抽象 - IMessagePublisher / IMessageSubscriber
  • ✅ 缓存/日志抽象 - ICacheService / ILoggerService
  • ✅ 微服务抽象 - 认证(ITokenService)、服务发现(IConsulService/IConsulHttpClient)、HTTP(IHttpClientService)、幂等、功能开关、请求上下文、发件箱、API 版本
  • ✅ AI 契约 ⭐ - IAIService / IAgentService / ICopilotClient / IAgentContextManager / IChatContextManager / IRAGService + Memory 三契约

核心组件

1. 实体与值对象 (Entities) — 命名空间 Healnet.Core.Entities

类型 说明
Entity<TKey> (abstract) 实体基类:TKey Id;重写 Equals/GetHashCode/==/!=;IEquatable<Entity<TKey>>。4.0.11 修复:Id 为 default(未持久化)时回退引用相等语义(原任意两个未持久化实体两两相等且哈希码相同,放入 HashSet/Dictionary 会互相覆盖);AuditableEntity/SoftDeleteEntity 继承同一实现自动受益
Entity (abstract) Entity<long> 便捷基类
AggregateRoot<TKey> (abstract) 继承 Entity<TKey>,支持领域事件收集:DomainEvents、AddDomainEvent/RemoveDomainEvent/ClearDomainEvents/DequeueDomainEvents
ValueObject (abstract) 值对象基类:基于 GetEqualityComponents() 的值相等性
AuditableEntity<TKey> (abstract) 可审计实体:CreatedAt/CreatedBy/UpdatedAt/UpdatedBy/IsDeleted/DeletedAt/DeletedBy
SoftDeleteEntity<TKey> (abstract) 软删除实体:IsDeleted/DeletedAt
IDomainEvent / DomainEvent 领域事件接口与基类:OccurredOn(UtcNow)、EventId
IDomainEventDispatcher / IDomainEventHandler<in TEvent> 领域事件分发抽象(实现在宿主/Infrastructure)

2. 异常体系 (Exceptions) — 命名空间 Healnet.Core.Exceptions

基类 HealnetException : Exception,含 int ErrorCode、string UserMessage、bool IsRetryable。

类型 HTTP 状态 ErrorCode
BadRequestException 400 400(可自定义)
BusinessException 400 可自定义
UnauthorizedException 401 —
ForbiddenException 403 —
NotFoundException 404 —
ValidationException 422 Dictionary<string,string[]> Errors(静态 WithError/WithErrors)

协议异常(带固定 ErrorCode,部分可重试):SqlInjectionException(4001)、PermissionDeniedException(4031)、ResourceNotFoundException(4041)、ValidationFailedException(4002)、DatabaseException(5001,可重试)、LLMException(5002,可重试)、TimeoutExceptionEx(5041,可重试)、RateLimitedException(4291,可重试)。

3. 接口抽象 (Interfaces) — 命名空间 Healnet.Core.Interfaces

接口 说明
IRepository<TEntity,TKey> : IReadOnlyRepository<...> 完整仓储:AddAsync/AddRangeAsync/UpdateAsync/UpdateRangeAsync/DeleteAsync(id)/DeleteAsync(entity)/DeleteRangeAsync
IReadOnlyRepository<TEntity,TKey> 查询:GetByIdAsync/GetAllAsync/GetPagedAsync(page,pageSize)/CountAsync/ExistsAsync/FindAsync/FindAllAsync
IUnitOfWork : IDisposable SaveChangesAsync(ct)/BeginTransactionAsync/CommitTransactionAsync/RollbackTransactionAsync/HasActiveTransaction
ICacheService GetAsync<T>/SetAsync<T>/RemoveAsync/ExistsAsync/GetOrSetAsync<T>/GetKeysByPatternAsync/RemoveByPatternAsync/ClearAsync/GetTtlAsync/GetAndDeleteAsync<T>(4.0.0 新增,对实现者破坏性)
ILoggerService Trace/Debug/Information/Warning/Error/Critical/Error(Exception,...)/Log(LogLevel,...)
IMessagePublisher PublishAsync<T>(exchange+routingKey / queue / 单消息 / 带 MessageOptions)
IMessageSubscriber Subscribe<T>/StartConsumingAsync/StopConsumingAsync
IService<TRequest,TResponse,TKey> 标准服务接口:GetByIdAsync/GetAllAsync/GetPagedAsync/CreateAsync/UpdateAsync/DeleteAsync,返回 ApiResponse 系列

4. AI 契约 ⭐ — 命名空间 Healnet.Core.AI

纯接口 + POCO,不引用任何 AI SDK。

接口:

接口 关键成员
IAIService ChatAsync(prompt[,contextId])、SummarizeAsync、TranslateAsync、ExecuteAgentAsync ⚠️[Obsolete]、ExecuteAgentWithToolsAsync ⚠️[Obsolete]、ClearContext、AIProvider GetCurrentProvider()
IAgentService ExecuteAsync/ExecuteWithToolsAsync/ChatAsync×2 ⚠️ 均 [Obsolete](执行链路死链路,恒抛 NotSupportedException);RegisterAgentAsync/RegisterToolAsync 可用(同名覆盖)
ICopilotClient ChatAsync/SummarizeAsync/TranslateAsync/ClearContext(推荐入口)
IAgentContextManager CreateContextAsync(agentName)/DeleteContextAsync/GetContextAsync→AgentContext?/ClearAllContextsAsync(仅服务于废弃的 Agent 链路,5.0 删除)
IChatContextManager CreateContextAsync()/DeleteContextAsync/GetContextAsync→ChatContext?/ClearAllContextsAsync(⚠️ 全库零消费方,5.0 整族删除)
IRAGService AddDocumentAsync/RemoveDocumentAsync/SearchDocumentsAsync(query,topK=5)→List<Document>/ChatWithRAGAsync(实现为演示级 Jaccard 词集重叠,非向量检索)

选项 / 枚举(POCO):

  • AIOptions:Provider(AIProvider)、Framework(AIFramework,⚠️ 只写不读的占位枚举)、ApiKey、Endpoint、ModelName("gpt-4o")、MaxTokens(4096)⚠️、Temperature(0.7)⚠️、TopP(0.9)⚠️、ContextWindowSize(8192)⚠️(⚠️ 四项 4.0.15 起标 [Obsolete]:未被任何实现接线,配置不生效)、HttpClientTimeoutSeconds(90,已接线)、RAG(RAGOptions)、AgentFramework(AgentFrameworkOptions,⚠️ 占位配置零读取)
  • enum AIProvider { SemanticKernel, MicrosoftAI, Custom }
  • enum AIFramework { SemanticKernel, AgentFramework, Hybrid }(⚠️ 占位,5.0 删除)
  • RAGOptions:Enabled(true)、TopK(5)、MaxContextLength(3000)
  • AgentFrameworkOptions:Endpoint、DeploymentName("gpt-4o")、EnableToolCalling(true)、MaxIterations(10)、Dictionary<string,string> Tools

上下文模型(POCO,框架无关):

  • AgentContext:ContextId/AgentName/List<AgentMessage> Messages/AddUserMessage/AddAssistantMessage/ClearHistory
  • AgentMessage:Role/Content/Timestamp/Metadata
  • ChatContext:仅含 List<ChatMessage> Messages(不依赖 Semantic Kernel 的 ChatHistory)、AddUserMessage/AddAssistantMessage/ClearHistory
  • ChatMessage:Role/Content/Timestamp
  • Document:Id/Content/Metadata/Score

5. AI 记忆契约 ⭐ — 命名空间 Healnet.Core.AI.Memory

Contracts(接口 + 配置/记录 POCO):

类型 说明
IShortTermMemoryStore L1 短期记忆:GetWindowAsync(sessionId)→List<ShortTermTurn>、AppendAsync、ClearAsync(默认基于 Redis)
IConversationRepository L2 关系型库:EnsureSchemaAsync/SaveSessionAsync/GetSessionAsync/SaveTurnAsync/GetRecentTurnsAsync/ListSessionsAsync。4.0.11 契约调整(对自行实现者破坏性,调用方 await 用法不变):SaveSessionAsync/SaveTurnAsync 返回 Task<bool>(失败返回 false 并保留日志,让编排层可感知静默丢数据);新增 CountTurnsAsync(COUNT 聚合,供 TurnNo 计算替代拉取 10 万条)
IMemoryOrchestrator 编排:BuildContextAsync(sessionId,userId,domain?,enableMemory)→MemoryContext、RecordTurnAsync(MemoryRecordInput)、GetHistoryAsync
MemoryContext List<ShortTermTurn> ShortTermHistory
MemoryOptions EnableShortTerm(true)、ShortTermWindowTurns(10)、ShortTermTtlMinutes(30)、EnableFullConversation(true)、ConversationDbConfigId("conversation")
MemoryRecordInput (record) SessionId/UserId/Domain?/DatabaseName?/UserQuery/AssistantResponse?/IsValid/RowCount/ErrorMessage?/DurationMs/TokensUsed
ShortTermTurn Role/Content/Ts(DateTime)

Entities(纯 POCO,无 ORM 特性;映射在 Infrastructure 的 SqlSugar Fluent):

  • ConversationSession:Id/SessionId/UserId/Domain?/DatabaseName?/Title?/Status(1=active)/CreatedAt/UpdatedAt
  • ConversationTurn:Id/SessionId/TurnNo/UserId/Domain?/DatabaseName?/UserQuery?/Response?/IsValid/RowCount/ErrorMessage?/TokensUsed/DurationMs/Status(1)/CreatedAt

6. 服务基类 (Services) — 命名空间 Healnet.Core.Services

类型 说明
BaseService (abstract) 持有 protected ILoggerService Logger;ValidateId/ValidateNotNull/ValidateNotEmpty/GetEntityOrThrowAsync/LogError/LogInformation
CrudService<TEntity,TRequest,TResponse,TKey> : BaseService, IService<...> 标准 CRUD 实现;抽象 MapToEntity/MapToResponse/UpdateEntity,虚 ValidateRequest

7. API 响应 (Responses) — 命名空间 Healnet.Core.Responses

类型 说明
ApiResponse (非泛型) Code/Message/Data/Timestamp/Path/IsSuccess;静态 Success/Fail/Unauthorized/Forbidden/NotFound/BadRequest
ApiResponse<T> 泛型版,静态 Success(T?,msg)/Fail(msg,code)/NotFound(msg) 等
PagedResponse<T> Code/Message/List<T> Data/Total/Page/PageSize/TotalPages/HasNextPage/HasPreviousPage;静态 Create(...)

8. 其他模块

| 模块 | 命名空间 | 说明 | |------|----------|------| | 全局异常中间件 | Core.Middleware | ExceptionHandlerMiddleware(捕获异常→ApiResponse,映射 400/401/403/404/422/500)。4.0.11 增强:补 HealnetException 基类分支(原 SqlInjection/PermissionDenied/ResourceNotFound/ValidationFailed/Database/LLM/Timeout/RateLimited 等协议子类全部落入兜底 500);ErrorCode → HTTP StatusCode 统一映射——100-599 原值直通、4031→403、4041→404、4291→429、其余 4xxx→400、5xxx→500、未知区间→500,消除 4031 等非法状态码直通 HTTP 的问题;app.UseExceptionHandlerMiddleware() | | 幂等性 | Core.Filters | [Idempotent] 特性(TtlSeconds=3600、HeaderName="Idempotency-Key")+ IIdempotencyStore | | API 版本 | Core.Versioning | [ApiVersion] 特性 + ApiVersionConstants(RouteTemplate/DefaultVersion="1.0"/VersionHeader="X-Api-Version") | | 发件箱 | Core.Outbox | OutboxMessage(OutboxMessageStatus 枚举:Pending/Delivered/DeadLetter)+ IOutboxStore| | 功能开关 |Core.Features|IFeatureFlagService(IsEnabledAsync/GetValueAsync<T>/GetEnabledFeaturesAsync)+ FeatureContext| | 请求上下文 |Core.Context|IRequestContext(TraceId/TenantId/UserId/UserName/ClientIp/UserAgent)+ DefaultRequestContext(AsyncLocal) | | 认证抽象 | Core.Authentication|ITokenService+JwtOptions(实现在 Infrastructure.Authentication) | | 服务发现抽象 | Core.Consul|IConsulService+IConsulHttpClient+ConsulOptions(实现在 Infrastructure.Consul;ConsulOptions支持唯一实例 ID 注册、gRPC 健康检查,以及 **4.0.10 新增**GrpcLegacyTagFallback(默认 false) / GrpcLegacyFallbackTag(默认 server),用于遗留 gRPC 实例发现回退) | | HTTP 抽象 | Core.Http|IHttpClientService+IHttpClientFactoryService+IHttpInterceptor(实现在 Infrastructure.Http) | | Skill | Core.Skill|ISkillLoader+SkillOptions(SkillStorageMode:Local/Oss)+ OssOptions` |

依赖关系

graph LR
    A[Healnet.Core] --> B[Healnet.Common]
    A --> C[Microsoft.Extensions.Logging.Abstractions]
    A --> D[Microsoft.AspNetCore.Http.Abstractions]
    A --> E[Microsoft.Extensions.Primitives]

⚠️ 注意:Core 仅依赖上述 3 个轻量 NuGet 包 + Common。无 Semantic Kernel / Microsoft.Extensions.AI / MediatR / SqlSugar / EF Core 等任何重量级依赖。

使用指南

1. 创建实体

using Healnet.Core.Entities;

public class User : Entity<long>
{
    public string Name { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
}

public class Product : AuditableEntity
{
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
}

public class Article : SoftDeleteEntity
{
    public string Title { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
}

2. 统一异常处理

using Healnet.Core.Exceptions;

throw new BusinessException("库存不足");                       // → 400
throw new NotFoundException($"用户 {userId} 不存在");          // → 404
throw new ValidationException(new List<string> { "邮箱格式不正确" });  // → 422
throw new ForbiddenException("无权访问此资源");                 // → 403

3. API 响应格式

using Healnet.Core.Responses;

// 成功响应(Data 泛型,Timestamp 构造时自动填充)
return ApiResponse<User>.Success(user, "查询成功");
return ApiResponse<List<User>>.Success(userList);

// 失败响应(工厂方法对应各 HTTP 语义)
return ApiResponse.Fail("操作失败");                  // code=500
return ApiResponse.BadRequest("参数错误");            // code=400
return ApiResponse.Unauthorized();                    // code=401
return ApiResponse.Forbidden();                       // code=403
return ApiResponse.NotFound("用户不存在");            // code=404

// 泛型版本(含可指定状态码的 SuccessResult)
var created = ApiResponse<User>.SuccessResult(user, 201);   // code=201
var failed  = ApiResponse<string>.Fail("boom");             // code=500, Data=null

// 分页响应
var paged = PagedResponse<User>.Create(users, page, pageSize, totalCount);

⚠️ IsSuccess 严格等于 Code == 200:SuccessResult(data, 201) 的 IsSuccess 为 false。 调用方以 IsSuccess 判断成功时,非 200 状态码(含 201/204)都会得到 false——按 Code 判断更稳妥。

文档可见性(4.0.13 起)

Core 4.0.13 起 csproj 开启 GenerateDocumentationFile,包内随附 lib/net10.0/Healnet.Core.xml。原因:SwaggerOptions.IncludeXmlComments 默认 true 但只在输出目录里找 *.xml——Core 此前不产 XML,ApiResponse 的契约注释写了也进不了 swagger schema,外部调用方看到的 code 只是无描述的 integer,于是把业务码误当成 HTTP 状态码来读。

服务端拿到这个文件的方式见 examples/ 模板 csproj:PackageReference ... GeneratePathProperty="true" + 构建/发布两个 Target 从包目录定向复制。不要改用 CopyDocumentationFilesFromPackages——它会把 100+ 个三方包文档一并复制(实测 109 个 / 46MB),且 Swashbuckle 每次生成文档都会重扫这些文件。

4. 仓储接口

using Healnet.Core.Interfaces;

public interface IUserRepository : IRepository<User, long>
{
    Task<User?> GetByEmailAsync(string email);
    Task<IEnumerable<User>> GetActiveUsersAsync();
}

5. 服务基类

using Healnet.Core.Services;
using Healnet.Core.Interfaces;

public class UserService : BaseService, IUserService
{
    private readonly IRepository<User, long> _repository;
    public UserService(ILoggerService logger, IRepository<User, long> repository) : base(logger)
        => _repository = repository;

    public async Task<User> GetByIdAsync(long id)
    {
        ValidateId(id);
        var user = await _repository.GetByIdAsync(id);
        if (user is null) throw new NotFoundException($"用户 {id} 不存在");
        return user;
    }
}

6. 全局异常处理中间件

// Program.cs — 推荐用 Core 版(功能最全,支持 Path/Timestamp)
app.UseExceptionHandlerMiddleware();

7. 使用 AI 契约(消费方视角)

using Healnet.Core.AI;

public class ChatController
{
    private readonly ICopilotClient _copilot;
    public ChatController(ICopilotClient copilot) => _copilot = copilot;

    public async Task<string> Ask(string prompt)
        => await _copilot.ChatAsync(prompt);   // 实现由 Infrastructure.AI 注入
}

NuGet 包信息

属性 值
PackageId Healnet.Core
当前版本 4.0.14
目标框架 net10.0
依赖项目 Healnet.Common
主要依赖 Microsoft.Extensions.Logging.Abstractions [9.0.0,11.0.0)、Microsoft.AspNetCore.Http.Abstractions [2.2.0,3.0.0)、Microsoft.Extensions.Primitives [9.0.0,11.0.0)
仓库 内部仓库

版本历史

以下变更说明整理自 Healnet.Core.csproj 的 PackageReleaseNotes,具体日期以各发布记录为准(本文不杜撰日期)。

版本 变更说明
v4.0.14 XML 注释缺陷修复(只动注释,IL 无变化):① 修净 79 条 CS1570——注释里直接写 Entity<TKey>、Task<ApiResponse<T>> 这类未转义泛型尖括号,XML 非法会让编译器丢弃该成员的整段文档(实测:把某成员注释放回未转义写法,Healnet.Core.xml 的 member 条目 558→557、该类型彻底消失;修复后恢复)。② 修 4 条标记与签名不一致:ISkillLoader.WatchSkillChanges 的 <param name="cancellationToken"> 指向不存在的参数(CS1572)、IArchiveService.RequestAsync 缺该 param 标记(CS1573)、MemoryRecordInput 的 /// 写在 record 位置参数上(CS1587,非合法文档目标)——改为类型级 <param> 并补全 11 个参数说明。③ NoWarn 从「1591;1570;1572;1573;1587」收窄为只抑制 1591,将来注释格式回退会重新告警而不是静默丢文档
v4.0.13 开启 XML 注释文档生成,并重写 ApiResponse 的语义注释(仅文档,无运行时变更)。① 此前 Core 不产出 Healnet.Core.xml,而 SwaggerOptions.IncludeXmlComments 默认 true、只在输出目录里找 *.xml,导致统一响应的契约说明永远进不了 swagger schema description(code 只是个无描述的 integer);现启用 GenerateDocumentationFile。② code 注释明确为「业务状态码,判定业务结果请用它,不要只看 HTTP 状态码」;success 标注「等价于 Code == 200」;类级注释给出两种形态并存的样例(HTTP 200 + body.code=404、HTTP 400 + body.code=400)。③ 随包携带 lib/net10.0/Healnet.Core.xml;CS1591(公开成员缺注释)按行业惯例抑制
v4.0.12 ExceptionHandlerMiddleware 补齐「响应已开始写出」保护(P2):原实现捕获全局异常后无条件改写 ContentType/StatusCode 并写错误体,当异常发生在响应已开始输出之后(SSE 流式推送、大文件下载中途失败、分块响应)再改响应头会抛 InvalidOperationException,导致中间件自身崩溃、连接异常中断并产生二次异常。现检测 response.HasStarted:已开始写出时仅记 Warning 并直接返回(由客户端感知连接中断),未开始写出时行为完全不变。⚠️ 4.0.11 的发布包不含此修复(修复晚于打包时刻),请升级到 4.0.12+
v4.0.11 代码审查缺陷批量修复:① Entity.Equals/GetHashCode Id 为 default 时回退引用相等语义;② ExceptionHandlerMiddleware 补 HealnetException 基类分支 + ErrorCode→HTTP StatusCode 映射(4031→403、4041→404、4291→429 等);③ IConversationRepository 契约调整(对自行实现者破坏性):SaveSessionAsync/SaveTurnAsync 返回 Task<bool>、新增 CountTurnsAsync。已知限制:全部契约接口补 CancellationToken 归 5.0
v4.0.10 ConsulOptions 新增 GrpcLegacyTagFallback(默认 false)与 GrpcLegacyFallbackTag(默认 server):允许 gRPC 服务发现对“无 grpc-port Meta”的遗留框架实例回退使用 Address:Port,实现新库客户端与老 gRPC 服务互通;默认关闭,行为完全向后兼容
v4.0.6 三库版本重新对齐至统一 4.0.6(消除版本分叉,无新增代码变更/公开 API 变更,源码与 4.0.3 一致)
v4.0.0 破坏性主版本:① ICacheService 新增 GetAndDeleteAsync<T>(对实现 ICacheService 的外部类破坏性,框架 RedisService 已实现);② ApiKeyAuthenticationHandler.CustomTokenResolver 委托签名由同步 Func<string,ClaimsPrincipal?> 改为异步 Func<string,Task<ClaimsPrincipal?>>(⚠️ 该 Handler 实际位于 Infrastructure,见上方说明);③ AIOptions 新增 HttpClientTimeoutSeconds(非破坏性,新增选项)
v3.1.0 随 Healnet 统一升版至 3.1.0(无本库代码变更,依赖 Healnet.Common 3.1.0 的 IFileService 预签名 URL 扩展)
v3.0.1 新增 API Key 认证 Handler 支持(CustomTokenResolver 与 client_source=workbuddy claim,类型位于 Infrastructure)、Consul 支持唯一实例 ID 注册与 gRPC 健康检查、新增 GrpcClientBase 泛型基类(类型位于 Infrastructure)、移除孤立的 AuthorizationInterceptor/AuthorizationService
v3.0.0 随 Healnet 统一升版至 3.0.0(破坏性变更来自 Healnet.Common:AESCrypto 移除无参重载、AESDecrypt 改返回元组)
v2.0.7 三库版本统一 2.0.7;BusinessConfig 全套迁出至业务项目;BusinessExample 迁出;ConversationArchive 泛化
v2.0.6 三库版本统一 2.0.6
v2.0.3 统一三库版本号;升级目标框架至 net10.0;更新所有依赖包至最新稳定版
v2.0.1 依赖包版本升级,修复若干已知问题
v2.0.0 重大版本更新,目标框架从 net8.0 升级至 net10.0,全面更新依赖包版本

许可证

MIT License

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Healnet.Core:

Package Downloads
Healnet.Infrastructure

Healnet.Infrastructure 是 Healnet 框架的基础设施层类库,提供各种基础设施服务的封装和集成,包括 Consul 服务发现、Redis 缓存、RabbitMQ 消息队列、gRPC、Elasticsearch、Milvus 向量数据库、SQLSugar ORM、JWT 认证、YARP 反向代理、OpenTelemetry 可观测性、Serilog 日志框架、ClickHouse 列式数据库等。

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.0.15 0 11/4/2026
4.0.14 34 11/3/2026
4.0.13 38 11/3/2026
4.0.12 42 11/3/2026
4.0.11 52 11/3/2026
4.0.10 174 9/15/2026
4.0.9 184 8/13/2026
4.0.8 132 8/13/2026
4.0.7 146 8/13/2026
4.0.6 118 8/10/2026
4.0.3 131 8/10/2026
4.0.0 157 8/3/2026
3.1.0 144 7/24/2026
3.0.1 144 7/23/2026
3.0.0 140 7/16/2026
2.0.7 138 7/10/2026
2.0.5 142 7/8/2026
2.0.3 145 6/30/2026
2.0.0 148 6/29/2026
1.7.3 142 6/29/2026
Loading failed

v4.0.15: AI 契约存活状态标注(架构评审 2026-11-04 结论的编译期落地,仅加 [Obsolete] 特性与注释,无行为变更)。① IAgentService 执行链路 4 个方法(ExecuteAsync/ExecuteWithToolsAsync/ChatAsync 两个重载)标 [Obsolete]:当前实现未接入任何 AI 后端,调用恒抛 NotSupportedException(详见 Infrastructure 4.0.40);RegisterAgentAsync/RegisterToolAsync 仍可用。② IAIService 的 ExecuteAgentAsync/ExecuteAgentWithToolsAsync 标 [Obsolete](同上,路由到死链路)。③ AIOptions 的 MaxTokens/Temperature/TopP/ContextWindowSize 标 [Obsolete]:四个推理参数全库零接线(配置不生效),5.0 将以 ChatOptions/GenerationDefaults 形式正式接线;HttpClientTimeoutSeconds 已接线不受影响。期间推荐入口:ICopilotClient.ChatAsync。破坏性变更:无([Obsolete] 为警告级,编译照常通过);5.0 契约 2.0 时上述成员将删除或重做。 v4.0.14: XML 注释缺陷修复(只动注释,IL 无变化,运行时行为/公开签名/序列化形状全不变)。① 修净 79 条 CS1570——注释里直接写 Entity<TKey>、Task<ApiResponse<T>> 这类未转义的泛型尖括号,XML 非法会让编译器【丢弃该成员的整段文档】:逐行转义为 &lt; / 保留 <c> 等合法标签。已实测因果:把某成员注释放回未转义写法会立刻重现 CS1570,且 Healnet.Core.xml 的 member 条目 558→557(该类型彻底消失,Swagger 与 IntelliSense 都拿不到它),修复后恢复 558。② 修 4 条标记与签名不一致:ISkillLoader.WatchSkillChanges 的 <param name="cancellationToken"> 指向不存在的参数(CS1572);IArchiveService.RequestAsync 缺 cancellationToken 的 param 标记(CS1573);MemoryRecordInput 把 /// 注释写在 record 位置参数上(CS1587,非合法文档目标)——改为类型级 param 标记并补全 11 个参数的说明。③ NoWarn 从「1591;1570;1572;1573;1587」收窄为只抑制 1591:这几类已修净,今后再写出格式错误的注释会重新告警,而不是静默丢文档。 v4.0.13: 开启 XML 注释文档生成,并重写 ApiResponse 的语义注释(仅文档,无运行时变更)。① 此前 Core 不产出 Healnet.Core.xml,而 SwaggerOptions.IncludeXmlComments 默认 true、只在输出目录里找 *.xml,结果「统一响应 ApiResponse 的契约说明」永远进不了 Swagger schema description(文档里 code 只是一个光秃秃的 integer)。现启用 GenerateDocumentationFile,ApiResponse 等公开契约的 summary 会随 XML 文件流进 Swagger。② ApiResponse 的 code 注释明确为「业务状态码,判定业务结果请用它,不要只看 HTTP 状态码」;success 说明「等价于 Code == 200」;类级注释补两种形态并存的说明与样例——HTTP 200 + body.code=404(Controller 直接返回 ApiResponse.NotFound,如模板 GET /api/products/{id})与 HTTP 400 + body.code=400(模型校验 / 显式 StatusCode(...) / 异常经 ExceptionHandlerMiddleware 按 code 映射)。属性、方法签名、序列化形状、IsSuccess 判定口径全部不变。④ 本包现已随包携带 lib/net10.0/Healnet.Core.xml(上面开启 GenerateDocumentationFile 的直接结果);服务端模板改为用 GeneratePathProperty 从包目录只复制该文件到输出目录,供 SwaggerOptions.IncludeXmlComments 读取,不再依赖 CopyDocumentationFilesFromPackages(后者会把 100+ 三方包文档一起复制,实测 109 个 / 46MB)。 ③ 开启文档生成后按需抑制 XML 注释类告警(CS1591 缺失、CS1570/1572/1573/1587 既有注释的格式与 param 失配问题)——这些是历史注释问题,与本次文档修复无关,清理另开任务;抑制后编译仍为 0 警告 0 错误。 v4.0.12: ExceptionHandlerMiddleware 补齐「响应已开始写出」保护(P2)。原实现捕获全局异常后无条件改写 ContentType/StatusCode 并写错误体;当异常发生在响应已开始输出之后(SSE 流式推送、大文件下载中途失败、分块响应),再改响应头会抛 InvalidOperationException,导致中间件自身崩溃、连接异常中断并在日志产生二次异常。现检测 response.HasStarted:已开始写出时仅记 Warning 并直接返回(由客户端感知连接中断),不再尝试改写响应;未开始写出时行为完全不变。注意:4.0.11 的发布包不含此修复(该修复晚于 4.0.11 打包时刻),请升级到 4.0.12。 v4.0.11: 代码审查缺陷批量修复。① Entity.Equals/GetHashCode(正确性):Id 为 default 时回退引用相等语义(原任意两个未持久化实体两两相等且哈希码相同,放入 HashSet/Dictionary 会互相覆盖);AuditableEntity/SoftDeleteEntity 继承同一实现自动受益。② ExceptionHandlerMiddleware(HTTP 语义):补 HealnetException 基类分支(原 SqlInjectionException/PermissionDeniedException/ResourceNotFoundException/ValidationFailedException/DatabaseException/LLMException/TimeoutExceptionEx/RateLimitedException 等子类全部落入兜底 500);BusinessException.ErrorCode 与响应码统一经映射后写入 HTTP StatusCode——规则为 100-599 原值直通、4031→403、4041→404、4291→429、其余 4xxx→400、5xxx→500、未知区间→500——消除 4031 等非法状态码直通 HTTP 的问题。③ IConversationRepository 契约调整(对自行实现该接口的外部代码为破坏性变更,调用方 await 用法不变):SaveSessionAsync/SaveTurnAsync 返回 Task<bool>(失败返回 false 并保留日志,让编排层可感知静默丢数据);新增 CountTurnsAsync(COUNT 聚合,供 TurnNo 计算替代拉取10万条)。已知限制:全部契约接口补 CancellationToken 归 5.0。v4.0.10: ConsulOptions 新增 GrpcLegacyTagFallback(默认 false)与 GrpcLegacyFallbackTag(默认 server):允许 gRPC 服务发现对"无 grpc-port Meta 但 Tags 含指定 tag"的遗留框架实例(如 .NET Core 3.1 MicroCloud,主端口即 h2c gRPC)回退使用 Address:Port,实现新库客户端与老 gRPC 服务互通。默认关闭,行为完全向后兼容。v4.0.6: 三库版本重新对齐至统一 4.0.6(消除版本分叉,无新增代码变更/公开 API 变更,源码与 4.0.3 一致)。v4.0.0: 破坏性主版本(建议消费方锁 4.x)。破坏性变更:① ICacheService 新增 GetAndDeleteAsync<T> 方法(对实现 ICacheService 的外部类破坏性,框架 RedisService 已实现);② ApiKeyAuthenticationHandler.CustomTokenResolver 委托签名由同步 Func<string,ClaimsPrincipal?> 改为异步 Func<string,Task<ClaimsPrincipal?>>(对消费方破坏性,赋值处须改为 async);③ AIOptions 新增 HttpClientTimeoutSeconds(非破坏性,新增选项)。v3.1.0: 随 Healnet 统一升版至 3.1.0(无本库代码变更,依赖 Healnet.Common 3.1.0 的 IFileService 预签名 URL 扩展)。v3.0.1: 新增 API Key 认证 Handler(ApiKeyAuthenticationHandler/AuthenticationExtensions,支持自定义 Token 解析器与 client_source=workbuddy claim);Consul 支持唯一实例 ID 注册与 gRPC 健康检查(ConsulOptions/IConsulService);新增 GrpcClientBase 泛型基类;移除孤立的细粒度角色授权(AuthorizationInterceptor/AuthorizationService);AIServiceExtensions 调整。v3.0.0: 随 Healnet 统一升版至 3.0.0(破坏性变更来自 Healnet.Common:AESCrypto 移除无参重载、AESDecrypt 改返回元组)。v2.0.7: 三库版本统一 2.0.7;BusinessConfig 全套迁出至业务项目;BusinessExample 迁出;ConversationArchive 泛化。v2.0.6: 三库版本统一 2.0.6。v2.0.3: 统一三库版本号;升级目标框架至 net10.0;更新所有依赖包至最新稳定版。v2.0.1: 依赖包版本升级,修复若干已知问题。v2.0.0: 重大版本更新,目标框架从 net8.0 升级至 net10.0,全面更新依赖包版本。