skills/csharp-aspnetcore/SKILL.md
ASP.NET Core 開發規範:DI Lifetime、HttpClient、回應格式與 API 版本控制。當偵測到 ASP.NET Core 專案或使用者要求撰寫 API 端點時自動套用。
npx skillsauth add CloudyWing/ai-dotfiles csharp-aspnetcoreInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
當偵測到 ASP.NET Core 專案(含 Microsoft.AspNetCore 相依套件)或使用者要求撰寫 API 端點、Controller、Middleware 時,請自動套用以下規範。
| Lifetime | 適用情境 |
| --- | --- |
| Singleton | 無狀態、執行緒安全的服務(如 IOptions<T>、記憶體快取) |
| Scoped | 每次 HTTP 請求一個實例;DbContext 必須使用此 Lifetime |
| Transient | 輕量、無狀態的短暫任務型服務 |
IServiceScopeFactory 手動建立 Scope。new HttpClient(),會造成 Socket 耗盡問題。IHttpClientFactory 或具名/型別化用戶端(Named / Typed Client)注入。// ✅ 正確
builder.Services.AddHttpClient<MyService>();
public class MyService(HttpClient httpClient) { }
// ❌ 錯誤
public void DoWork() {
using HttpClient client = new();
}
Results.Problem(...) 或 Results.ValidationProblem(...) 產生標準化錯誤。// ✅ 正確
return Results.Problem(
title: "資源不存在",
statusCode: StatusCodes.Status404NotFound
);
// ❌ 錯誤
return Results.Json(new { error = "Not found" }, statusCode: 404);
Asp.Versioning.Http),產生或修改端點時必須加入對應版本路由前綴(如 /api/v1/)。IConfiguration 並以字串索引取值,會散落硬編碼 Key 且缺乏型別安全。IOptions<T> / IOptionsSnapshot<T> / IOptionsMonitor<T> 注入。| 介面 | Lifetime | 適用情境 |
| --- | --- | --- |
| IOptions<T> | Singleton | 應用程式啟動後不會變更的設定 |
| IOptionsSnapshot<T> | Scoped | 每次請求重新讀取(支援熱更新,不可用於 Singleton) |
| IOptionsMonitor<T> | Singleton | 需要即時感知設定變更(支援 OnChange 回呼) |
// 註冊
builder.Services.Configure<SmtpOptions>(
builder.Configuration.GetSection("Smtp")
);
// 注入
public class EmailService(IOptions<SmtpOptions> options) {
private readonly SmtpOptions smtp = options.Value;
}
BackgroundService:實作長期執行迴圈的背景工作首選(覆寫 ExecuteAsync,搭配 CancellationToken)。IHostedService:需要精確控制 StartAsync / StopAsync 生命週期時使用(如啟動前的初始化任務)。AddHostedService<T>() 或 AddSingleton<IHostedService, T>() 註冊;不要在 Controller / Service 中自行 Task.Run 長期工作。// ✅ 正確:BackgroundService 長期輪詢
public class DataSyncService(IDbContextFactory<AppDbContext> factory) : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
await using AppDbContext db = await factory.CreateDbContextAsync(stoppingToken)
.ConfigureAwait(false);
// 同步邏輯...
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken).ConfigureAwait(false);
}
}
}
tools
產生或補齊 .gitattributes,統一行尾處理、二進位識別與 lock files 標記,保留既有自訂偏好。
development
產生或補齊前端 Lint 設定(Prettier + ESLint Flat Config),統一格式化與程式碼品質規則,保留既有自訂偏好。
testing
依據事實校閱報告修改技術文件:以事實層為不可違反的約束,由改檔者負責表達層的措辭與行文連貫。Use when the user asks to apply fact-check results to a document, or to edit a document based on a previously produced fact-check-report.md.
data-ai
多份資料檔整合流程。當需要將兩份以上的資料檔(如 JSON、CSV)合併、補齊闕漏欄位或去重成單一檔案時使用。以 dry-run、筆數核對與抽樣比對降低整合錯誤。