Asp.Net Core 中的“虚拟目录”实现(2)

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "VirtualPath": [ { "RealPath": "F:\\test1", //真实路径 "RequestPath": "/test", "Alias": "first" }, { "RealPath": "F:\\test2", //真实路径 "RequestPath": "/test", "Alias": "second" }, { "RealPath": "F:\\test3", //真实路径 "RequestPath": "/test", "Alias": "third" } ] }

创建对应的实体映射:

public class VirtualPathConfig { public List<PathContent> VirtualPath { get; set; } } public class PathContent { public string RealPath { get; set; } public string RequestPath { get; set; } public string Alias { get; set; } }

在PhysicalFileProvider上封装一层,加入别名便于获取:

public class MyFileProvider : PhysicalFileProvider { public MyFileProvider(string root, string alias) : base(root) { this.Alias = alias; } public MyFileProvider(string root, Microsoft.Extensions.FileProviders.Physical.ExclusionFilters filters, string alias) : base(root, filters) { this.Alias = alias; } /// <summary> /// 别名 /// </summary> public string Alias { get; set; } }

调整Startup.ConfigureServices和Startup.Configure:

public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.Configure<VirtualPathConfig>(Configuration); var config = Configuration.Get<VirtualPathConfig>().VirtualPath; config.ForEach(f => { services.AddSingleton(new MyFileProvider(f.RealPath,f.Alias)); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var config = Configuration.Get<VirtualPathConfig>().VirtualPath; config.ForEach(f => { app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(f.RealPath), RequestPath =f.RequestPath }); }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }

最后,调整调用方式,即可。

[HttpGet] public object GetFiles([FromServices] IEnumerable<MyFileProvider> fileProviders) { var file = fileProviders.FirstOrDefault(x=>x.Alias=="first").GetFileInfo("mybook.txt"); if (file.Exists) { return ReadTxtContent(file.PhysicalPath); } return 0; }

最后

  物理文件系统的抽象通过PhysicalFileProvider这个FileProvider来实现,借助IFileProvider的特点,其实可以扩展实现轻量“云盘”的功能了,而不仅仅只是实现IIS虚拟目录功能。搞定,今晚不加班!

到此这篇关于Asp.Net Core 中的“虚拟目录”实现的文章就介绍到这了,更多相关Asp.Net Core 虚拟目录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/076610a89160d6e13437453a988a4846.html