ASP.NET Coreでのパイプライン設定とサービス構成

以下に、ASP.NET Coreのパイプライン設定と主要なサービス構成方法を紹介します。

MVCオプションの設定


services.Configure<MvcOptions>(options =>
{
    options.Filters.Add<GlobalActionFilter>();
    options.Filters.Add<GlobalExceptionFilter>();
});

圧縮機能の設定と追加


services.AddResponseCompression(opts =>
{
    opts.Providers.Add<GzipCompressionProvider>();
});

services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Fastest;
});

app.UseResponseCompression();

レスポンスキャッシュの設定


services.AddResponseCaching(options =>
{
    options.UseCaseSensitivePaths = true;
});

app.UseResponseCaching();

APIコントローラーとモデル検証


services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        var errors = new List<ErrorModel>();
        foreach (var key in context.ModelState.Keys)
        {
            foreach (var error in context.ModelState[key].Errors)
            {
                errors.Add(new ErrorModel(key, error.ErrorMessage));
            }
        }
        return new JsonResult(new ApiMessage { Errors = errors, Success = false });
    };
});

グローバルコンテキストとHTTPコンテキストの取得


services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

動的ルーティングの設定


services.AddSingleton<CustomRouteHandler>();

app.UseEndpoints(endpoints =>
{
    endpoints.MapDynamicControllerRoute<CustomRouteHandler>("{controller}/{action}.custom");
});

メモリーキャッシュの設定


services.AddMemoryCache();

セッションの設定


services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(10);
});

app.UseSession();

URLリライトの設定


app.UseRewriter(new RewriteOptions()
    .AddRedirect("^$", "swagger")
    .AddRedirect("old/", "new/"));

JSONシリアライズのカスタマイズ


services.Configure<JsonOptions>(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    options.JsonSerializerOptions.Converters.Add(new CustomDateTimeConverter());
});

CORS(クロスオリジンリクエスト)の設定


services.AddCors(options =>
{
    options.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
    });
});

app.UseCors("AllowAll");

認証と承認の設定

認証の設定


services.AddAuthentication(options =>
{
    options.DefaultScheme = "Bearer";
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters();
});

app.UseAuthentication();

承認の設定


services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy =>
    {
        policy.RequireClaim("Role", "Admin");
    });
});

services.AddScoped<IAuthorizationHandler, CustomAuthorizationHandler>();

app.UseAuthorization();

静的ファイルの提供


app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Static")),
    OnPrepareResponse = ctx =>
    {
        ctx.Context.Response.Headers["Cache-Control"] = "public, max-age=86400";
    }
});

健康チェックの設定


services.AddHealthChecks();
app.UseHealthChecks("/health");

タグ: aspnetcore MVC pipeline

5月20日 21:30 投稿