【问题标题】:ASP.NET Core API 500 Internal Server Error when uploading file on IIS在 IIS 上上传文件时 ASP.NET Core API 500 内部服务器错误
【发布时间】:2019-05-28 23:31:22
【问题描述】:

我正在开发一个需要上传文件功能的 API 项目。当我在 localhost 上运行项目并尝试上传文件时,它可以正常工作,但是当我发布项目并将其部署到 IIS 上时,上传功能无法正常工作并产生 500 内部服务器错误。

    [Authorize]
[Route("api/[controller]")]
[ApiController]
public class UserFilesController : ControllerBase
{
    private IConfiguration configuration;

    public UserFilesController(IConfiguration iConfig)
    {
        configuration = iConfig;
    }

    [HttpPost]
    public async Task<IActionResult> PostFormData([FromForm]IFormFile file)
    {
        var dict = new Dictionary<string, string>();
        HttpContext.User.Claims.ToList()
           .ForEach(item => dict.Add(item.Type, item.Value));

        string userid = dict.ElementAt(2).Value;

        FileConverter fileConverter = new FileConverter();

        if (file == null || file.Length == 0)
            return Content("file not selected");

        var path = Path.Combine(
                    Directory.GetCurrentDirectory(), "File",
                    file.FileName);

        string ext = Path.GetExtension(file.FileName);
        string newFileName = Guid.NewGuid().ToString();
        var filePath = Path.Combine(Directory.GetCurrentDirectory(), "File", newFileName+ext);

        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        fileConverter.ConvertToPdf(filePath, newFileName);

        var pdfPath = Path.Combine(
                    Directory.GetCurrentDirectory(), "File",
                    newFileName+".pdf");

        DateTime ExpiredOn = DateTime.Now.AddDays(1);
        DateTime CreatedOn = DateTime.Now;
        string fileUrl = "/File/" + newFileName + ext;
        string pdfUrl = "/File/" + newFileName + ".pdf";

        using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
        {
            connection.Open();
            try
            {
                string createdon = CreatedOn.ToString("yyyy-MM-dd HH:mm:ss").Replace(".", ":");
                string expiredon = ExpiredOn.ToString("yyyy-MM-dd HH:mm:ss").Replace(".", ":");
                var value = connection.Execute(
                    "INSERT INTO uf (ufid, name, oriformat, fileurl, pdfurl, createdon, expiredon, isdeleted, systemuserid) VALUES (uuid_generate_v4(), '" + file.FileName + "', '" + ext.Replace(".","") + "', '" + fileUrl + "', '" + pdfUrl + "', '" + createdon + "', '" + expiredon + "', false, '" +userid+ "');"
                    );
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }
        }

        TableUserFileBaru result = new TableUserFileBaru();

        using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
        {
            connection.Open();
            try
            {
                var value = connection.Query<TableUserFileBaru>(
                    "select * from uf where systemuserid = '"+userid+"' order by createdon desc;"
                    );
                result = value.First();
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }
        }

        string ori_format = result.oriformat.ToString().Replace(".", "");

        PostUserFileResp resp = new PostUserFileResp();
        resp.UFId = result.ufid.ToString();
        resp.Name = result.name;
        resp.OriFormat = ori_format;
        resp.FileURL = result.fileurl;
        resp.PdfURL = result.pdfurl;
        resp.CreatedOn = result.createdon;
        resp.ExpiredOn = result.expiredon;
        resp.SystemUserId = result.systemuserid;
        resp.IsDeleted = result.isdeleted;

        return Ok(resp);
    }
}

更新: 在我按照 ArunPratap 的步骤显示错误详细信息后,我收到了以下消息。

An unhandled exception occurred while processing the request.UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\NetCore\File\7ebb3a76-f194-41f2-8a4b-a576308856aa.pdf' is denied. System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)

在我之后 有谁知道如何解决它? 谢谢。

【问题讨论】:

  • 尝试记录异常将清楚地了解导致问题的原因。并尝试使用 POSTMAN REST 客户端。
  • 检查您的服务器日志,看看出了什么问题。日志的存在是有原因的,因此您应该习惯于使用它们来弄清楚发生了什么。在不知道哪里出了问题的情况下,我们只能猜测可能出了什么问题。
  • 尝试启用Log creation and redirection 并与我们分享您遇到的错误。
  • 我刚刚更新了帖子

标签: c# iis asp.net-core asp.net-core-webapi


【解决方案1】:

您可以创建一个名为ASPNET_ENV 的系统环境变量并将其值设置为Development 并调用UseDeveloperExceptionPage() 方法。这将显示错误的详细信息,然后,您可以修复它

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

更新

现在你得到request.UnauthorizedAccessException: Access to the path denied 尝试转到App_Data 文件夹属性并添加具有读写权限的ASPNET 用户

Look for instruction

【讨论】:

  • 我在 .net core 上比较新,但是当我使用 postman 调用它时,错误详细信息会显示在哪里?
  • 是的,当您发布并调用它时,它会显示错误详细信息
  • 我更新了帖子,也许你能帮我解决错误
猜你喜欢
  • 2014-01-11
  • 2017-03-07
  • 1970-01-01
  • 2020-11-16
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
相关资源
最近更新 更多