为什么此ASP.NET Core代码在远程主机上不起作用

时间:2019-08-14 20:45:30

标签: c# asp.net-core

我有一个可以在本地主机上使用的Angular网站。当我将其上传到远程主机时,它会失败且没有错误。只是不保存任何文件。

我已经在网上搜索了答案。不高兴。

这永远不会在本地Visual Studio 2019或远程计算机上返回错误。

在Microsoft网站上找到了基本代码。看了很多棱角分明的地方

[Route("api/[controller]")]
[ApiController]
public class UploadController : ControllerBase
{
    private IHostingEnvironment env;

    public UploadController(IHostingEnvironment hostingEnvironment)
    {
        env = hostingEnvironment;
    }

    [HttpPost, DisableRequestSizeLimit]
    public async Task<IActionResult> Upload()
    {
        try
        {
            var files = Request.Form.Files;

            if (files.Count < 1)
            {
                return BadRequest();
            }

            if (files.Any(f => f.Length == 0))
            {
                return BadRequest();
            }

            foreach (var file in files)
            {
                string folderName = $"Project_{file.FileName}";
                string webRootPath = env.WebRootPath;
                string newPath = Path.Combine(Startup.documentPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }

                if (file.Length > 0)
                {
                    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).Name.Trim('"');
                    string fullPath = Path.Combine(newPath, fileName);

                    if (System.IO.File.Exists(fullPath))
                    {
                        System.IO.File.Delete(fullPath);
                    }

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

            return Ok("All the files are successfully uploaded.".csConverToJSON());
        }
        catch (Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }
}

0 个答案:

没有答案