Search code examples
asp.netowinkatana

Modify contents of static files


how can I modify the response before it is sent to the client when I use Microsoft.Owin.StaticFiles?

        FileServerOptions options = new FileServerOptions();
        options.FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(Path.Combine(Environment.CurrentDirectory, "Content/"));
        options.DefaultFilesOptions.DefaultFileNames = new string[] { "index.htm", "index.html" };
        options.StaticFileOptions.OnPrepareResponse = (r) =>
        {
            r.OwinContext.Response.WriteAsync("test");
        };
        options.EnableDefaultFiles = true;
        app.UseFileServer(options);

"test" is never written into the response. I tried to use another middleware which waits until the StaticFiles Middleware is executed:

        app.Use((ctx, next) =>
        {
            return next().ContinueWith(task =>
            {
                return ctx.Response.WriteAsync("Hello World!");
            });
        });

        FileServerOptions options = new FileServerOptions();
        options.FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(Path.Combine(Environment.CurrentDirectory, "Content/"));
        options.DefaultFilesOptions.DefaultFileNames = new string[] { "index.htm", "index.html" };
        options.EnableDefaultFiles = true;
        app.UseFileServer(options);

But this didn't work. How can I modify the response?


Solution

  • On prepare response is not meant to modify the content of a static file. You are only allowed to add the header.

    I needed to pass some variable that change to a static web page and I got around it by using On prepare response and passed the variables as cookies for the page. This works nicely for a few variables but if you want to change a page significantly you are better of using mvc components.

             appBuilder.UseStaticFiles(new StaticFileOptions()
                                      {
                                          RequestPath = new PathString(baseUrl),
                                          FileSystem = new PhysicalFileSystem(staticFilesLocation),
                                          ContentTypeProvider = new JsonContentTypeProvider(),
                                          OnPrepareResponse = r => r.OwinContext.Response.Cookies.Append("baseUrl",_webhostUrl)
                                      });