如何解决如何将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文件:
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
}
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。