使用 ASP.Net 核心向客戶端提供 index.html 的標準方法是在類的方法中使用實體上app.UseStaticFiles();的中間件。這提供了來自 wwwroot 檔案夾的靜態 index.html 檔案。有沒有辦法向客戶端提供一個 index.html,它是根據請求在代碼中動態生成的?IApplicationBuilderConfigureStartUp
uj5u.com熱心網友回復:
有一種方法可以更改從靜態檔案夾提供的 SPA 檔案內容。
您應該執行以下操作:
- 更新您對 的使用,它應該為該屬性
UseStaticFiles提供一個 lambda ;OnPrepareResponse請參閱此MS 檔案 - 每次將靜態檔案回傳給客戶端時呼叫;
- 您可以分析檔案名以確保它是index.html;
- 您的代碼可以完全更改將回傳的內容。只需動態生成一個檔案來替換 index.html,然后通過寫入流將其寫入回應體。如果您的寫作失敗,您可能需要在修改和回傳之前清除或保存原始正文內容。
請參閱代碼示例以幫助您入門:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426961.html
