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

前端 未结 2 1635
渐次进展
渐次进展 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:12

    Yes, it is possible. Just get the path to your app folder and the pass it to configuration or whoever else needs it:

    public class Startup
    {
        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            var wwwrootRoot = env.WebRootPath;
            var appRoot = appEnv.ApplicationBasePath;
    
    0 讨论(0)
  • 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<string> 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:

      <ItemGroup>
        <None Include="AppData\*" CopyToPublishDirectory="PreserveNewest" />
      </ItemGroup>
    
    0 讨论(0)
提交回复
热议问题