"Access to the path 'C:\home\site\wwwroot\dataModel.csv' is denied." 在 .NET Core 应用中,部署在 Azure 中

"Access to the path 'C:\\home\\site\\wwwroot\\dataModel.csv' is denied." in a .NET Core app, deployed in Azure

我有一个 ASP.NET Core API 应用程序,它通过 HangFire 运行一些后台进程。其中一个过程包括 将 csv 文件写入 wwwroot 文件夹,如下所示:

public async Task Work(PerformContext context)
        {
            var latestLikes = await this.likeRepository
                .All()
                .Select(l => new LatestLikesServiceModel
                {
                    UserId = l.UserId,
                    BeatId = l.BeatId,
                })
                .ToListAsync();

            var modelPath = this.webHostEnvironment.ContentRootPath + "\dataModel.csv";
            using (var writer = new StreamWriter(modelPath))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csv.WriteRecords(latestLikes);
            }
        }

在 localhost 中它工作得很好,但是当我在 azure 中部署它时,HangFire 日志 returns: "System.UnauthorizedAccessException","ExceptionMessage":"访问路径 'C:\home\site\wwwroot\dataModel.csv' 被拒绝。"
我该如何解决这个问题?

下面的代码在我这边工作正常:

using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionApp97
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ExecutionContext ec,
            ILogger log)
        {
            string str = ec.FunctionAppDirectory;
            log.LogInformation(str);
            using (var reader = new StreamReader(str+ @"\filename.txt"))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    log.LogInformation(line);
                }
            }
            return new OkObjectResult(str);
        }
    }
}

经过一周的研究,我终于找到了解决方案
我应该提到我将 Azure DevOps 用于 CI & CD。
默认情况下,azure 应用程序服务部署为 zip(这切断了对文件系统的直接访问)我必须做的是将部署方法更改为 Web 部署(Additional Deployment Options),我终于可以访问文件系统。 更多描述性信息,请参考:
https://tomasherceg.com/blog/post/azure-app-service-cannot-create-directories-and-write-to-filesystem-when-deployed-using-azure-devops#comments