71 lines
2.2 KiB
C#
71 lines
2.2 KiB
C#
|
using System;
|
|||
|
using System.IO;
|
|||
|
using System.Threading.Tasks;
|
|||
|
using Microsoft.AspNetCore.Builder;
|
|||
|
using Microsoft.AspNetCore.Hosting;
|
|||
|
using Microsoft.Extensions.Configuration;
|
|||
|
using Microsoft.Extensions.DependencyInjection;
|
|||
|
using Microsoft.Extensions.FileProviders;
|
|||
|
using Microsoft.Extensions.Hosting;
|
|||
|
|
|||
|
namespace ETFileServer
|
|||
|
{
|
|||
|
public class Startup
|
|||
|
{
|
|||
|
private IConfiguration Configuration { get; }
|
|||
|
|
|||
|
public Startup(IConfiguration configuration)
|
|||
|
{
|
|||
|
Configuration = configuration;
|
|||
|
}
|
|||
|
|
|||
|
public void ConfigureServices(IServiceCollection services)
|
|||
|
{
|
|||
|
services.AddControllers();
|
|||
|
|
|||
|
// 1. 从配置中获取文件根目录路径
|
|||
|
string fileRootPath = Configuration["DirectoryPath"];
|
|||
|
if (string.IsNullOrEmpty(fileRootPath))
|
|||
|
{
|
|||
|
throw new InvalidOperationException("DirectoryPath is not configured in appsettings.json.");
|
|||
|
}
|
|||
|
|
|||
|
// 2. 解析为绝对路径
|
|||
|
string fullPath = Path.GetFullPath(fileRootPath);
|
|||
|
if (!Directory.Exists(fullPath))
|
|||
|
{
|
|||
|
// 在启动时检查目录是否存在,如果不存在则创建
|
|||
|
Directory.CreateDirectory(fullPath);
|
|||
|
Console.WriteLine($"Warning: Root directory not found. Created directory at: {fullPath}");
|
|||
|
}
|
|||
|
|
|||
|
// 3. 创建并注册一个 PhysicalFileProvider 作为单例服务
|
|||
|
// 这样整个应用都可以安全地使用它来访问文件
|
|||
|
var provider = new PhysicalFileProvider(fullPath);
|
|||
|
services.AddSingleton<IFileProvider>(provider);
|
|||
|
}
|
|||
|
|
|||
|
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
|||
|
{
|
|||
|
if (env.IsDevelopment())
|
|||
|
{
|
|||
|
app.UseDeveloperExceptionPage();
|
|||
|
}
|
|||
|
|
|||
|
app.UseRouting();
|
|||
|
|
|||
|
app.UseEndpoints(endpoints =>
|
|||
|
{
|
|||
|
endpoints.MapControllers();
|
|||
|
});
|
|||
|
|
|||
|
// 对于任何未匹配到Controller的请求,直接返回404 Not Found
|
|||
|
app.Run(context =>
|
|||
|
{
|
|||
|
context.Response.StatusCode = 404;
|
|||
|
return Task.CompletedTask;
|
|||
|
});
|
|||
|
}
|
|||
|
}
|
|||
|
}
|