4

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?

kpko
  • 131
  • 11

1 Answers1

6

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)
                                  });
Marcom
  • 4,621
  • 8
  • 54
  • 78
  • Note that "_Cookies do not provide isolation by port_" (more https://stackoverflow.com/a/16328399/968003). Not a biggie, but can cause frictions when devs swap between running the front-end under `Kestrel` and `ng serve`. – Alex Klaus Mar 08 '21 at 00:08
  • I think it would be better if the web server set this cookie - you wouldn't need to set up asp.net. – Ian Warburton Apr 12 '22 at 14:50