in asp.net 5 is it possible to store and read custom files in approot instead of wwwroot?

前端 未结 2 1688
渐次进展
渐次进展 2021-02-14 11:02

when you deploy an asp.net5/mvc6 app there is the wwwroot folder where web assets like css, js, images belong, and there is approot folder where packages and source code belong.

2条回答
  •  天命终不由人
    2021-02-14 11:30

    The accepted answer is correct, but since a ASP.NET Core 1.0 release a few things have changed so I thought I'd write a new clear things up a bit.

    What I did was create a folder in my project called AppData. You can call it anything you like.

    Note: it's not in wwwroot because we want to keep this data private.

    Next, you can use IHostingEnvironment to get access to the folder path. This interface can be injected as a dependency into some kind of helper service and what you end up with is something like this:

    public class AppDataHelper
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        private const string _appDataFolder = "AppData";
    
        public AppDataHelper(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
    
        public async Task ReadAllTextAsync(string relativePath)
        {
            var path = Path.Combine(_hostingEnvironment.ContentRootPath, _appDataFolder, relativePath);
    
            using (var reader = File.OpenText(path))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }
    

    Additionally, to get things to deploy correctly I had to add the AppData folder to the publishOptions include list in project.json.

    As mentioned in the comments, to deploy AppData folder correctly in ASP.NET MVC Core 2 (using *.csproj file, instead of project.json), syntax is as follows:

      
        
      
    

提交回复
热议问题