在asp.net核心中访问被拒绝的文件

时间:2018-02-22 17:08:59

标签: c# iis asp.net-core


当我将项目发布到iis并且我确实在浏览器上上传了一张图片,因此此操作失败并在logger sysytem

中显示此错误
  

发生了未处理的异常:访问路径' C:\ Inetpub \ vhosts \ qarbal.com \ back.qarbal.com \ wwwroot \ images \ UserProfile \ pic_50.jpg'被拒绝.System.UnauthorizedAccessException:访问路径' C:\ Inetpub \ vhosts \ qarbal.com \ back.qarbal.com \ wwwroot \ images \ UserProfile \ pic_50.jpg'被拒绝。      在System.IO.FileStream.OpenHandle(FileMode模式,FileShare共享,FileOptions选项)      在System.IO.FileStream..ctor(String path,FileMode mode,FileAccess access,FileShare share,Int32 bufferSize,FileOptions options)

ActionController的

[HttpPost("[action]")]
public async Task<IActionResult> EditPhoto()
{
    var uploadsRootFolder = Path.Combine(_env.WebRootPath, "images\\UserProfile");
    var files = Request.Form.Files;     
    foreach (var file in files)
    {       
        if (file == null || file.Length == 0)
        {
            continue;
        }
        var filePath = Path.Combine(uploadsRootFolder, queryModel.Name  + files[0].FileName);
        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(fileStream).ConfigureAwait(false);
        }
    }
    return Json("ok");  
}

startup.cs

public void Configure(ILoggerFactory loggerFactory, IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles();
}

如何解决此异常?

2 个答案:

答案 0 :(得分:4)

右键点击wwwroot文件夹 - &gt;属性 - &gt;安全标签 - &gt;点击Edit按钮 - &gt;输入IIS AppPool\DefaultAppPool用户 - &gt;点击Check names - &gt;好的 - &gt;然后给它Write permission

答案 1 :(得分:-1)

工作正常...

string fileName = file_name+".pdf";

           string files = System.IO.Path.Combine("pdf/") + fileName;
            if (!System.IO.File.Exists(files))
            {
                return RedirectToAction("index", new { message = "File Not Found" });

            }
            else
            {

                byte[] fileBytes = System.IO.File.ReadAllBytes(files);
                return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, files);

            }