Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure client caching when using OWIN static files

Tags:

c#

caching

owin

This is my Startup.cs where I map my index page to the route '/app'.

...
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using Microsoft.Owin.Diagnostics;
[assembly: OwinStartup(typeof(conApi.Startup))]

namespace conApi
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ////Set static files
            ConfigureFiles(app);

            //Enable Cors
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        }

        public void ConfigureFiles(IAppBuilder app)
        {
            app.Map("/app", spa =>
            {
                spa.Use((context, next) =>
                {
                    context.Request.Path = new PathString("/index.html");

                    return next();
                });

                spa.UseStaticFiles();
            });
        }
    }
}

It works like a charm but I don't know how to configure the client caching. I would like to know how to set the Expires header if that is possible when using OWIN static files?

SOLUTION
Tratcher provided the link to the StaticFilesOptions class documentation etc which lead me to a solution. Added the StaticFilesOptions to the ConfigureFiles method like this:

public void ConfigureFiles(IAppBuilder app)
{
    var staticFileOptions = new StaticFileOptions
    {
        OnPrepareResponse = (StaticFileResponseContext) =>
        {
            StaticFileResponseContext.OwinContext.Response.Headers.Add("Cache-Control",new[] { "public", "max-age=1000" });
        }
    };

    app.Map("/app", spa =>
    {
        spa.Use((context, next) =>
        {
            context.Request.Path = new PathString("/index.html");

            return next();
        });

        spa.UseStaticFiles(staticFileOptions);
    });
}
like image 639
Marcus Höglund Avatar asked Jun 23 '16 11:06

Marcus Höglund


1 Answers

You can pass a StaticFilesOptions to UseStaticFiles. On the options use the OnPrepareResponse event to customize your responses. See http://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin.StaticFiles/StaticFileOptions.cs

like image 123
Tratcher Avatar answered Oct 13 '22 01:10

Tratcher