繁体   English   中英

ASP.Net Core - 动态生成 index.html

[英]ASP.Net Core - Dynamically generate index.html

使用 ASP.Net Core 向客户端提供 index.html 的标准方法是使用中间件app.UseStaticFiles(); StartUp class 的Configure方法中的IApplicationBuilder实例上。这提供了 wwwroot 文件夹中的 static index.html 文件。 有没有办法向客户端提供 index.html,它是根据请求在代码中动态生成的?

有一种方法可以更改从 static 文件夹提供的 SPA 文件内容。

您应该执行以下操作:

  1. 更新您对UseStaticFiles的使用,它应该为OnPrepareResponse属性提供 lambda; 请参阅此MS DOC
  2. static文件每次返回给客户端时调用;
  3. 您可以分析文件名,确保它是index.html;
  4. 您的代码可以完全更改将返回的内容。 只需要动态生成一个文件替换index.html,写入一个stream作为响应body即可。如果写入失败,可能需要清空或保存原body内容再修改返回。

请参阅代码示例以帮助您入门:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM