如何将HTML文件及其样式加载到浏览器API中

问题描述

我正在使用API​​在Asp.Net Core中处理Web应用程序。我遇到一个问题,即我无法通过API将HTML文件加载到Web应用程序中。我尝试通过以下方式加载HTML

var fileContents = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Content/HelloWorld.html"));
        var response = new HttpResponseMessage();
        response.Content = new StringContent(fileContents.ToString());
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
        return response;

在API控制器中,但未成功。 HTML文件位于其支持CSS文件的外部目录中。 谁能帮我将文件加载到浏览器中。

解决方法

HttpResponseMessage用于旧版ASP.NET MVC Web API,在ASP.NET Core Web API中,您可以像下面这样进行操作:

控制器:

[Route("api")]
[ApiController]
public class TestController : ControllerBase
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public TestController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpGet("GetHtml")]
    public IActionResult Index()
    {
        var path = Path.Combine(_hostingEnvironment.WebRootPath,"Content","Hello.html");
        var fileStream = System.IO.File.OpenRead(path);
        return File(fileStream,"text/html");
    }
}

静态文件应位于 wwwroot 文件夹下

enter image description here

在html文件中引用.css文件:

Hello.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../Content/MyCss.css" />
    <title></title>
</head>
<body>
    <h1>Hello World</h1>
    <h2>Hello World</h2>
    <h3>Hello World</h3>
    <h4>Hello World</h4>
</body>
</html>

MyCss.css:

h1{
    color: black
}
h2{
    color:rebeccapurple
}
h3 {
    color: greenyellow
}
h4 {
    color: salmon
}

结果:

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...