首页 > 解决方案 > 如何将 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 文件的外部目录中。谁能帮我将文件加载到浏览器中。

标签: htmlapiasp.net-coreasp.net-core-webapi

解决方案


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文件夹下

在此处输入图像描述

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

你好.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
}

结果:

在此处输入图像描述


推荐阅读