【问题标题】:ASP.NET Core 3.1 static files cannot be accessedASP.NET Core 3.1 静态文件无法访问
【发布时间】:2020-06-25 08:00:16
【问题描述】:

我有一些 JSON 数据配置文件,我希望将它们作为静态文件联机并在我的 Web 服务初始化时读取它们。因此,我希望从我的代码内部访问它们,而不是将它们公开给外部访问。

按照说明(如下)我将它们放在 /wwwroot/Static 文件夹中并在 Startup.Configure() 中使用 app.UseStaticFiles();,然后我尝试使用“~/Static/*.json”表示法通过 HTML 和 C# 代码读取它们但它不适用于 C# 代码

本地时,我收到错误:DirectoryNotFoundException: 找不到路径的一部分'...\Repos\VS2019\my-project-folder\~ \静态\filename.json'。

因此,~ 符号不会转换为 wwwroot 文件夹名称。

在线(作为 Azure 应用服务)我得到:HTTP ERROR 500

什么我做错了什么?

【问题讨论】:

    标签: asp.net-core static


    【解决方案1】:

    使用 HostingEnvironment 获取物理位置:

    public HomeController(IHostingEnvironment hostingEnvironment)
        {
            string data= System.IO.File.ReadAllText(hostingEnvironment.WebRootPath.ToString()+ @"\Static\test.json");
        }
    

    如果应用程序是 Web Api,则使用 ContentRoot 而不是 WebRootPath。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2020-11-26
    • 2019-10-26
    • 2018-02-03
    相关资源
    最近更新 更多