Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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от 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:

  1. Save the file - .NET automatically recompiles
  2. Check the terminal - Look for compilation output in the "Backend: ASP.NET Core API" terminal
  3. 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 - Runs dotnet watch run with 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 .Result or .Wait() on async methods
  • ❌ Forgetting CancellationToken parameter
  • ❌ 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 *.csproj for version)
  • Azure.AI.Projects.Agents — ProjectsAgentVersion, DeclarativeAgentDefinition, AgentAdministrationClient
  • Azure.AI.Extensions.OpenAI — ProjectOpenAIClient, ProjectConversationsClient, ProjectResponsesClient

Sub-namespaces: Azure.AI.Projects.Agents,

Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить writing-csharp-code с