将 DownloadFile 当中的代码封装成单独的方法
时间: 2024-03-21 10:40:45 浏览: 14
好的,以下是一个将 `DownloadFile` 方法封装成单独的方法的示例代码:
```csharp
public class FileController : ControllerBase
{
private readonly ILogger<FileController> _logger;
public FileController(ILogger<FileController> logger)
{
_logger = logger;
}
[HttpGet("download")]
public async Task<IActionResult> DownloadFile(string fileName)
{
try
{
var fileContent = await GetFileContent(fileName);
if (fileContent == null)
{
return NotFound();
}
return File(fileContent.Content, fileContent.ContentType, fileContent.FileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "下载文件出错");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
private async Task<FileContentResult> GetFileContent(string fileName)
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Files", fileName);
if (!System.IO.File.Exists(filePath))
{
return null;
}
var fileContent = await System.IO.File.ReadAllBytesAsync(filePath);
var contentTypeProvider = new FileExtensionContentTypeProvider();
contentTypeProvider.TryGetContentType(fileName, out string contentType);
return new FileContentResult(fileContent, contentType ?? "application/octet-stream")
{
FileDownloadName = fileName
};
}
}
```
在上面的代码中,我们将原来的代码封装成了一个名为 `GetFileContent` 的私有方法,该方法返回一个 `FileContentResult` 对象,其中包括文件的内容、文件类型和文件名。
在 `DownloadFile` 方法中,我们首先调用 `GetFileContent` 方法获取文件内容。如果文件不存在,我们将返回 `null`。
在返回文件流之前,我们使用 `FileContentResult` 类型来封装文件内容,并设置文件的下载名称。