Web API 加载内容文件

Web API load Content file

我从事 WebApi 项目,但我不明白如何加载我在解决方案中创建的文件。 这是我要加载和阅读的基本 json 文件。

TextReader tr = new StreamReader("file.json");

此代码无效。它在网站的文件夹中搜索,在 IIS 中,但我的文件不存在。 如何将我的文件复制到正确的位置? 我对它的工作原理有点困惑。

我将文件 "Build Action" 更改为 'Content',将 "Copy to Output" 更改为 "Copy always"

您需要使用 Server.MapPath 将虚拟路径映射到服务器上的物理路径。试试这个:

string path = Path.Combine(Server.MapPath("jsonFileDirName"), "file.json");
TextReader tr = new StreamReader(path);

有关 Server.MapPath 的更多信息可在此处找到:https://docs.microsoft.com/en-us/dotnet/api/system.web.httpserverutility.mappath?view=netframework-4.7.2