【问题标题】:How to load an html file along with its styles into a browser API如何将 html 文件及其样式加载到浏览器 API 中
【发布时间】:2020-12-01 05:21:27
【问题描述】:

我正在使用 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 文件的外部目录中。 谁能帮我将文件加载到浏览器中。

【问题讨论】:

    标签: html api asp.net-core asp.net-core-webapi


    【解决方案1】:

    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
    }
    

    结果:

    【讨论】:

    • 谢谢@mj1313。我已经检查过了,但风格没有得到。有没有办法加载样式文件?
    • 嗨@AnonymousDev,你需要在你的html文件中引用你的css文件,我已经更新了我的答案。
    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多