Home > Mobile >  ASP.Net Core - Dynamically generate index.html
ASP.Net Core - Dynamically generate index.html

Time:02-17

The standard way to provide an index.html to the client with ASP.Net core is to use the middleware app.UseStaticFiles(); on IApplicationBuilder instance in the Configure method of the StartUp class. This provides a static index.html file from the wwwroot folder. Is there a way to provide an index.html to the client, that is dynamically generated in code on request?

CodePudding user response:

There is a way to change the SPA files content served from the static folder.

You should do the following:

  1. update your usage of UseStaticFiles, it should have a lambda provided for the OnPrepareResponse property; See this MS DOC
  2. It is called every time the static file is returned to the client;
  3. You can analyze the file name to ensure it is index.html;
  4. Your code can completely change the content that will be returned. Just generate a file dynamically to replace index.html, and write it as a response body by writing to a stream. You might need to clear or save original body content before modifying and returning it if your writing has failed.

See code example to get you started:

var staticFileOptions = new StaticFileOptions
{
    OnPrepareResponse = context =>
    {
        // Only for Index.HTML file
        if (context.File.Name == "index.html") {
            var response = context.Context.Response;
            var str = "This is your new content";
            var jsonString = JsonConvert.SerializeObject(str);
            // modified stream
            var responseData = Encoding.UTF8.GetBytes(jsonString);
            var stream = new MemoryStream(responseData);
            // set the response body
            response.Body = stream;
        }
    }
};

app.UseStaticFiles(staticFileOptions);
  • Related