有了Asp.NET Core,环境中方便的寻路功能就消失了。HttpContext和HttpServerUtility已被删除。缓存框架中的应用程序存储也消失了。我不再能够(以代码形式)假设我的服务器正在使用IIS,或者甚至在Windows机器上运行它。
而且我没有数据库;我有一组JSON文件。由于该问题范围之外的原因,不能将其存储在数据库中。
如何读写服务器上的文件?
在新的ASP.NET Core部署环境中,我们有2个文件夹appRoot和wwwroot
我们通常只将文件放置在我们打算直接与http请求一起使用的wwwroot文件夹下。因此,如果要直接提供json文件(即由客户端js占用),则可以将它们放在此处,否则将在appRoot下使用其他文件夹。
我将在下面显示如何解析这两种情况的路径,即示例代码如何将json字符串保存到appRoot或wwwroot下的文件夹中。在两种情况下,都将您的位置视为相对于其中一个文件夹的虚拟路径,即/ some / folder / path,其中第一个/代表appRoot或wwwroot
public class MyFileProcessor
{
public MyFileProcessor(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
hostingEnvironment = env;
appEnvironment = appEnv;
appRootFolder = appEnv.ApplicationBasePath;
}
private IHostingEnvironment hostingEnvironment;
private IApplicationEnvironment appEnvironment;
private string appRootFolder;
public void SaveJsonToAppFolder(string appVirtualFolderPath, string fileName string jsonContent)
{
var pathToFile = appRootFolder + appVirtualFolderPath.Replace("/", Path.DirectorySeparatorChar.ToString())
+ fileName;
using (StreamWriter s = File.CreateText(pathToFile))
{
await s.WriteAsync(jsonContent);
}
}
public void SaveJsonToWwwFolder(string virtualFolderPath, string fileName string jsonContent)
{
var pathToFile = hostingEnvironment.MapPath(virtualFolderPath) + fileName;
using (StreamWriter s = File.CreateText(pathToFile))
{
await s.WriteAsync(jsonContent);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句