writing-csharp-code
БесплатноБез исполняемых скриптовНе проверенProvides C# and ASP.NET Core coding standards for this repository. Use when writing or modifying C# code, implementing API endpoints, configuring middleware…
от microsoft-foundry★ 137 звёзд на GitHubОб этом скилле
C# Coding Standards
Goal: Write clean, secure ASP.NET Core code with proper authentication
Hot Reload Development Workflow
The backend runs in watch mode (dotnet watch run). When you edit C# code:
- Save the file - .NET automatically recompiles
- Check the terminal - Look for compilation output in the "Backend: ASP.NET Core API" terminal
- Verify via console logs - New requests will use updated code immediately
VS Code Tasks (use Run Task command or check terminal panel):
Backend: ASP.NET Core API- Runsdotnet watch runwith live recompilation- Logs are visible directly in VS Code terminal
No restart needed - Just edit, save, and test. Watch for compilation errors in the terminal.
Testing changes: Use Playwright browser tools to make requests and check browser console logs, or call endpoints directly.
Minimal API Patterns
Use typed request models, CancellationToken, and IHostEnvironment:
app.MapPost("/api/endpoint", async (
RequestModel request,
MyService service,
IHostEnvironment env,
CancellationToken cancellationToken) =>
{
try
{
var result = await service.ProcessAsync(request, cancellationToken);
return Results.Ok(result);
}
catch (Exception ex)
{
return ErrorResponseFactory.CreateFromException(ex, env);
}
})
.RequireAuthorization("RequireChatScope")
.WithName("EndpointName");
Authentication Setup
JWT Bearer with Entra ID:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
builder.Configuration.Bind("AzureAd", options);
options.TokenValidationParameters.ValidAudiences = new[]
{
builder.Configuration["AzureAd:ClientId"],
$"api://{builder.Configuration["AzureAd:ClientId"]}"
};
}, options => builder.Configuration.Bind("AzureAd", options));
Async Best Practices
// ✅ Use async/await with CancellationToken
public async Task<Result> ProcessAsync(Request req, CancellationToken ct)
{
return await _service.ExecuteAsync(req, ct);
}
// ❌ Never block on async
var result = _service.ExecuteAsync(req).Result; // WRONG
IAsyncEnumerable for Streaming
public async IAsyncEnumerable<string> StreamAsync(
string input,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var chunk in source.WithCancellation(cancellationToken))
{
yield return chunk;
}
}
Credential Strategy
TokenCredential credential = env.IsDevelopment()
? new ChainedTokenCredential(
new AzureCliCredential(),
new AzureDeveloperCliCredential()) // Supports 'azd auth login'
: new ManagedIdentityCredential(miClientId); // User-assigned MI in production
Why ChainedTokenCredential: Avoids DefaultAzureCredential's "fail fast" mode issues. Explicit, predictable credential chain.
IDisposable Pattern
public class MyService : IDisposable
{
private readonly SemaphoreSlim _lock = new(1, 1);
private readonly CancellationTokenSource _disposeCts = new();
private bool _disposed;
public void DoWork()
{
ObjectDisposedException.ThrowIf(_disposed, this);
// ...
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
// Cancel pending operations first
try { _disposeCts.Cancel(); }
catch (ObjectDisposedException) { }
_disposeCts.Dispose();
_lock.Dispose();
}
}
Error Responses (RFC 7807)
Use ErrorResponseFactory.CreateFromException() for consistent error responses.
See: backend/WebApp.Api/Models/ErrorResponse.cs
Common Mistakes
- ❌ Using
.Resultor.Wait()on async methods - ❌ Forgetting
CancellationTokenparameter - ❌ Missing
.RequireAuthorization()on endpoints - ❌ Exposing internal errors in production
- ❌ Forgetting disposal guards in
IDisposable
Project-Specific: Middleware Pipeline
Goal: Serve static files → validate auth → route APIs → SPA fallback
app.UseDefaultFiles(); // index.html for /
app.UseStaticFiles(); // wwwroot/* assets
app.UseCors(); // Dev only
app.UseAuthentication(); // Validate JWT
app.UseAuthorization(); // Enforce scope
// Map endpoints here
app.MapFallbackToFile("index.html"); // MUST BE LAST
Project-Specific: AgentFrameworkService
See: backend/WebApp.Api/Services/AgentFrameworkService.cs
SDK Packages:
Azure.AI.Projects— Main entry point, v2 Agents API (see*.csprojfor version)Azure.AI.Projects.Agents—ProjectsAgentVersion,DeclarativeAgentDefinition,AgentAdministrationClientAzure.AI.Extensions.OpenAI—ProjectOpenAIClient,ProjectConversationsClient,ProjectResponsesClient
Sub-namespaces: Azure.AI.Projects.Agents,
Установить writing-csharp-code в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл writing-csharp-code?
Provides C# and ASP.NET Core coding standards for this repository. Use when writing or modifying C# code, implementing API endpoints, configuring middleware, or working with authentication in the backend.
Как установить скилл writing-csharp-code?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл writing-csharp-code запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic