将文件复制到系统时,辅助方法 return 的数据是什么

what data to return from a helper method when copying a file to the system

我有一个辅助方法可以将文件复制到我的网络服务器上的文件夹中。

它有效,但我不太确定 return 调用它的方法。

现在 return 是真的...因为也许它不需要 return 任何东西?

辅助方法如下:

    public async Task<bool> CopyFile(IFormFile profileUpload, Guid profileId)
    {
        string path = @"D:\ProfilePics\" + profileId;

        if (!Directory.Exists(path))
        {
            DirectoryInfo di = Directory.CreateDirectory(path);
        }

        using (var fileStream = new FileStream(path, FileMode.Create))
        {
            await profileUpload.CopyToAsync(fileStream);
        }

        return true;
    }
    
    

我在 API 控制器中调用它:

    [HttpPost]
    public async Task<IActionResult> PostFormData([FromForm(Name = "file")] IFormFile profileUpload, Guid profileId)
    {

        if (await _gamerProfile.CopyFile(profileUpload, profileId))
        {
            return Ok();
        } else
        {
            return BadRequest("Please upload a valid file");

        }

    }

我的问题是,有没有更好的方法来处理这个问题? return 是对还是错还是我应该 return 另一个值,或者什么都没有?

谢谢!

我认为您可以在出现故障时改进控制器的结果。

它们是 BadRequest(400) 和 ServerError(500) 之间的差异。

错误的请求意味着他们是来自用户端的问题,并且用户没有任何理由在不更改请求的情况下重新发送。

Server Error 的情况下,这意味着它们是服务器中的当前问题,用户可以等待并重试。

另一个问题是您在控制器中检查 CopyFile 函数 return true 或 false。

但是在你的代码中你 return 只有 true,如果你有任何问题你将有一个异常,而不是 false

您可以在函数中添加 try/catch 和 return false 以防出错。