ASP.NET Core API 500 Internal Server Error when uploading file on IIS


Sandy Rizky

I'm working on an API project that needs functionality to upload files. When I run the project on localhost and try to upload the file, it works fine, but when I publish the project and deploy it on IIS, the upload doesn't work and produces a 500 Internal Server Error.

    [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);
    }
}

Update: After following ArunPratap's steps to display the error details, I got the following message.

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)

Does anyone after me know how to fix this? thanks.

Alan Pratap

You can create a system environment variable called ASPNET_ENVand set its value to Developmentand call the UseDeveloperExceptionPage()method. The error details will be displayed and you can then fix the error

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

Updates

Now you'll get permission request.UnauthorizedAccessException: Access to the path deniedto try going to App_Datafolder properties and adding an ASPNET user with read and write permissions.

looking for instructions

Related


ASP.NET Core Web API 500 Internal Server Error

Fear I am trying to build an API within the ASP.NET Core framework. I made a basic controller that just returns a string: namespace Dojo_Api.Controllers.Forum { //[Authorize] [Route("api/[controller")] public class ForumController : Controller

ASP.NET Core WebAPI 500 Internal Error in IIS 7.5

james I am trying to get this WebAPI to work. Well, use IIS. Everything works fine in IIS express, but when I publish it, especially 1 api request doesn't work. The url I am trying to access API/[Controller]/{date}/{integer}. I keep getting a 500 server error.

ASP.NET Core WebAPI 500 Internal Error in IIS 7.5

james I am trying to get this WebAPI to work. Well, use IIS. Everything works fine in IIS express, but when I publish it, especially 1 api request doesn't work. The url I am trying to access API/[Controller]/{date}/{integer}. I keep getting a 500 server error.

ASP.NET Core WebAPI 500 Internal Error in IIS 7.5

james I am trying to get this WebAPI to work. Well, use IIS. Everything works fine in IIS express, but when I publish it, especially 1 api request doesn't work. The url I am trying to access API/[Controller]/{date}/{integer}. I keep getting a 500 server error.

ASP.NET Core WebAPI 500 Internal Error in IIS 7.5

Brandon I am trying to get this WebAPI to work. Well, use IIS. Everything works fine in IIS express, but when I publish it, especially 1 api request doesn't work. The url I am trying to access API/[Controller]/{date}/{integer}. I keep getting a 500 server erro

ASP.NET Core WebAPI 500 Internal Error in IIS 7.5

james I am trying to get this WebAPI to work. Well, use IIS. Everything works fine in IIS express, but when I publish it, especially 1 api request doesn't work. The url I am trying to access API/[Controller]/{date}/{integer}. I keep getting a 500 server error.

ASP.NET Core WebAPI 500 Internal Error in IIS 7.5

james I am trying to get this WebAPI to work. Well, use IIS. Everything works fine in IIS express, but when I publish it, especially 1 api request doesn't work. The url I am trying to access API/[Controller]/{date}/{integer}. I keep getting a 500 server error.

ASP.NET Core WebAPI 500 Internal Error in IIS 7.5

james I am trying to get this WebAPI to work. Well, use IIS. Everything works fine in IIS express, but when I publish it, especially 1 api request doesn't work. The url I am trying to access API/[Controller]/{date}/{integer}. I keep getting a 500 server error.

ASP.NET IIS Application 500 Internal Server Error

Moon Ninja I have a very strange problem. I have a development environment where I develop an ASP.NET MVC application and everything works fine in this environment. In particular there is an AJAX call in the Application that calls the controller and passes the

ASP.NET Core hosting - 500 Internal Server Error

username I'm trying to publish as an ASP.NET Core project using a hosting provider that supports ASP.NET Core. I get a 500 Internal Server Error, which is pretty common. So I searched on the internet and various forums and checked processPath="%LAUNCHER_PATH%"

ASP.NET Core hosting - 500 Internal Server Error

username I'm trying to publish as an ASP.NET Core project using a hosting provider that supports ASP.NET Core. I get a 500 Internal Server Error, which is pretty common. So I searched on the internet and various forums and checked processPath="%LAUNCHER_PATH%"

ASP.NET Core hosting - 500 Internal Server Error

username I'm trying to publish as an ASP.NET Core project using a hosting provider that supports ASP.NET Core. I get a 500 Internal Server Error, which is pretty common. So I searched on the internet and various forums and checked processPath="%LAUNCHER_PATH%"

ASP.NET Core hosting - 500 Internal Server Error

username I'm trying to publish as an ASP.NET Core project using a hosting provider that supports ASP.NET Core. I get a 500 Internal Server Error, which is pretty common. So I searched on the internet and various forums and checked processPath="%LAUNCHER_PATH%"

ASP.NET Core hosting - 500 Internal Server Error

username I'm trying to publish as an ASP.NET Core project using a hosting provider that supports ASP.NET Core. I get a 500 Internal Server Error, which is pretty common. So I searched on the internet and various forums and checked processPath="%LAUNCHER_PATH%"

ASP.NET Core hosting - 500 Internal Server Error

username I'm trying to publish as an ASP.NET Core project using a hosting provider that supports ASP.NET Core. I get a 500 Internal Server Error, which is pretty common. So I searched on the internet and various forums and checked processPath="%LAUNCHER_PATH%"

asp.net core application. 500 Internal Server Error

David Edel I uploaded my website to godaddy windows hosted with plesk. All files are uploaded but I get an error: 500 Internal Server Error. There is a problem with the resource you are looking for and cannot be displayed. By researching the problem online, I

ASP.NET Core API-500 Internal Server Error, in production only

facelift I have developed an ASP.NET WebApi application. When I publish and test it to localhost IIS I get this error on one request: Response with status: 500 Internal Server Error for URL: http://localhost/api/COMI/NEW/158/3 web.config: <?xml vers

Asp.Net Core 2 Web API 500 Internal Server Error

Anil When I try to access the API through postman, send: localhost:5050/api/Auth/token body: {“ UserName”:“ jouverc”,“ Password”:“ P @ ssw0rd!” } This method: [Produces("application/json")] [Route("api/Auth")] public class AuthController : Controller { #r

ASP.NET Core API-500 Internal Server Error, in production only

facelift I have developed an ASP.NET WebApi application. When I publish and test it to localhost IIS I get this error on one request: Response with status: 500 Internal Server Error for URL: http://localhost/api/COMI/NEW/158/3 web.config: <?xml vers

ASP.NET Core API-500 Internal Server Error, in production only

facelift I have developed an ASP.NET WebApi application. When I publish and test it to localhost IIS I get this error on one request: Response with status: 500 Internal Server Error for URL: http://localhost/api/COMI/NEW/158/3 web.config: <?xml vers