html - 如何将 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文件夹下
引用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
}
结果:
推荐阅读
- android - 使用 JetPack Navigation 使用 recyclerview 启动片段
- json - Wildfly json-formatter 类名元数据
- forms - MS Access:带有复选框的表单过滤器以应用预定义的标准
- javascript - 如何在javascript中暂停视频的视频播放时长?
- json - 在 Go 中获取嵌套的 JSON 数据
- dataframe - 使用 z 分数进行异常值检测,但是
- java - 底部导航栏默认情况下如何切换到特定菜单项?
- java - Hibernate 5 中 org.hibernate.Hibernate.createBlob() 或 org.hibernate.Hibernate.createClob() 的替代方案?
- html5-video - 如何从 VLC 将 h264 视频文件流式传输到 html5 视频标签?
- reactjs - 如何将函数从角度传递到反应模态并在那里调用它?