ASP.NET Core API在IIS上传文件时出现500内部服务器错误

3

我正在开发一个API项目,需要上传文件的功能。当我在本地运行该项目并尝试上传文件时,它可以完美地工作。但是当我发布该项目并部署到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)

在我执行某项操作后,出现了一个错误提示。有人知道如何解决吗?谢谢。


1
尝试记录异常,可以清楚地了解导致问题的原因。同时也可以使用POSTMAN REST客户端进行尝试。 - Saineshwar Bageri - MVP
检查您的服务器日志以查看出了什么问题。这些日志存在是有原因的,所以您应该习惯使用它们来找出发生了什么事情。如果不知道哪里出了问题,我们只能猜测可能出了什么问题。 - poke
尝试启用日志创建和重定向,并分享您遇到的错误。 - Edward
我刚刚更新了帖子。 - Sandy Rizky
1个回答

5
您可以创建一个名为ASPNET_ENV的系统环境变量,并将其值设置为Development,然后调用UseDeveloperExceptionPage()方法。这将显示错误的详细信息,之后您就可以修复它了。
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

更新

如果你现在遇到request.UnauthorizedAccessException: Access to the path denied的问题,请尝试进入App_Data文件夹属性并添加ASPNET用户,赋予读写权限。

查看指南


我在 .NET Core 上相对较新,但是当我使用 Postman 调用它时,错误详情会显示在哪里? - Sandy Rizky
是的,当您发布并调用它时,它会显示错误详情。 - ArunPratap
我更新了帖子,也许你可以帮我解决这个错误。 - Sandy Rizky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接