要在ASP.NET Core控制器中读取静态HTML文件并返回给客户端,您可以使用以下解决方法:
private string ReadHtmlFile(string filePath)
{
using (var reader = new StreamReader(filePath))
{
return reader.ReadToEnd();
}
}
public IActionResult GetHtmlFile()
{
var filePath = "path_to_your_html_file.html";
var htmlContent = ReadHtmlFile(filePath);
return Content(htmlContent, "text/html");
}
在上面的代码中,您需要将“path_to_your_html_file.html”替换为实际的HTML文件路径。
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddControllers();
services.AddStaticFiles();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
https://localhost:port/controllerName/getHtmlFile
请将“port”替换为您的应用程序的端口号,并将“controllerName”替换为您的控制器的名称。
这样,当客户端访问“getHtmlFile”操作时,控制器将读取HTML文件的内容,并将其作为响应返回给客户端。