3

i am working on a API Project which require a functionality to upload a file. When i run the project on localhost and trying to upload a file it works perfectly, but when i publish the project and deploy it on IIS the upload functionality it's not working and produce 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 i followed ArunPratap's step to show the error detail i got this 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)

After i Did anyone know how to solve it? Thanks.

4
  • 1
    try to log the exception will get a clear view of what is causing an issue. and also give a try with POSTMAN rest client. Commented Jan 2, 2019 at 11:34
  • Check your server log to see what is going wrong. The logs are there for a reason so you should get accustomed to using them to figure out what is going on. Without knowing what is failing, we can just guess what could be wrong. Commented Jan 2, 2019 at 13:48
  • Try to enable Log creation and redirection and share us the error you got. Commented Jan 3, 2019 at 2:11
  • i just updated the post Commented Jan 3, 2019 at 2:32

1 Answer 1

5

You can create a System Environment variable named ASPNET_ENV and set its value to Development and call the UseDeveloperExceptionPage() method. that will show the details of the error and after that, you can fix that

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

Update

As now you are getting request.UnauthorizedAccessException: Access to the path denied Try to go to App_Data folder property and add ASPNET user with reading and write privileges

Look for instruction

Sign up to request clarification or add additional context in comments.

3 Comments

i am relatively new on .net core, but where will the error detail showed when i call it using postman?
yes when you publish and call it then it will show you the error details
i updated the post, maybe you can help me with the error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.