using System.IO; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; namespace ETFileServer { [Route("")] [ApiController] public class DownLoadController : Controller { private readonly IFileProvider _fileProvider; private readonly ILogger _logger; private readonly IConfiguration _configuration; public DownLoadController(ILogger logger, IFileProvider fileProvider, IConfiguration configuration) { _logger = logger; _fileProvider = fileProvider; _configuration = configuration; } [HttpGet("{*filePath}")] public IActionResult Get(string filePath) { if (string.IsNullOrEmpty(filePath)) { return BadRequest("A file path must be provided."); } var fileInfo = _fileProvider.GetFileInfo(filePath); if (!fileInfo.Exists || fileInfo.IsDirectory) { _logger.LogWarning($"File not found or is a directory: {filePath}"); return NotFound(); } // 检查文件大小是否超出限制 long maxFileSizeInBytes = _configuration.GetValue("MaxFileSizeMb", 100) * 1024 * 1024; if (fileInfo.Length > maxFileSizeInBytes) { _logger.LogWarning($"File '{filePath}' exceeds the size limit of {maxFileSizeInBytes} bytes."); return new StatusCodeResult(413); // 413 Payload Too Large } _logger.LogInformation($"Serving file: {fileInfo.PhysicalPath}"); return PhysicalFile(fileInfo.PhysicalPath, "application/octet-stream", fileInfo.Name); } public override void OnActionExecuting(ActionExecutingContext context) { var httpContext = context.HttpContext; if (httpContext.Request.Method != "GET") { context.Result = new StatusCodeResult(405); return; } if (httpContext.WebSockets.IsWebSocketRequest) { context.Result = new BadRequestResult(); return; } if (httpContext.Request.HasFormContentType) { context.Result = new BadRequestResult(); return; } } public override void OnActionExecuted(ActionExecutedContext context) { } } }