Mantalog

~ blog of the Mantarou, by the Mantarou, for the Mantarou ~

ASP.NET Coreでブラウザキャッシュを無効にする

キャッシュが有効になっていると、画像を更新してもブラウザ上に反映されないことがある。
開発中は邪魔なので無効にすると便利。

/* Startup.cs */
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        // ここから↓↓
        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = context =>
            {
                context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
                context.Context.Response.Headers.Add("Pragma", "no-cache");
                context.Context.Response.Headers.Add("Expires", "-1");
            }
        });
        // ここまで追加↑↑
    }