如果使用Asp.net core來實現一個能夠訪問其它電腦上的資源
如何將靜態文件注入到項目中
在startup.cs文件的Configure方法中寫入:
app.UseStaticFiles();//提供將wwwroot目錄開放訪問,例如:http://localhost:52723/css/site.css將訪問wwwroot目錄下的css目錄中的site.css文件
這方法的默認路徑就是wwwroot目錄
- 如何使用自定義的文件路徑
在startup.cs文件的Configure方法中寫入: -
app.UseStaticFiles(new StaticFileOptions()//自定義自己的文件路徑,例如提供訪問D盤下的Study目錄,http://localhost:52723/MyStudy/README.md將訪問D盤的Study目錄中的README.md文件 { FileProvider = new PhysicalFileProvider(@"D:\Study"),//指定實際物理路徑 RequestPath = new PathString("/MyStudy")//對外的訪問路徑 });
如何瀏覽目錄的文件與文件夾
首先在startup.cs文件的Configure方法中寫入:
app.UseDirectoryBrowser(new DirectoryBrowserOptions()//提供文件目錄訪問形式
{
FileProvider = new PhysicalFileProvider(@"D:\Study"),
RequestPath = new PathString("/Study")
});
-
瀏覽目錄以及訪問文件
app.UseFileServer(new FileServerOptions()//直接開啟文件目錄訪問和文件訪問
{
EnableDirectoryBrowsing = true,//開啟目錄訪問
FileProvider = new PhysicalFileProvider(@"D:\Git"),
RequestPath = new PathString("/Git")
});
/// <summary>
/// 全盤符文件服務
/// </summary>
/// <param name="app"></param>
public static void UseLocalService(this IApplicationBuilder app)
{
DriveInfo[] driveInfos = DriveInfo.GetDrives();
foreach (DriveInfo drive in driveInfos)
{
string requestPath = drive.Name.Replace(":\\", "");
FileServerOptions fileServerOptions = new FileServerOptions
{
EnableDirectoryBrowsing = true,
//RequestPath = $"/{requestPath}",
FileProvider = new PhysicalFileProvider(drive.RootDirectory.FullName)
};
fileServerOptions.StaticFileOptions.DefaultContentType = "application/x-msdownload";//
fileServerOptions.StaticFileOptions.ServeUnknownFileTypes = true;
FileExtensionContentTypeProvider exten = new FileExtensionContentTypeProvider();
exten.Mappings.Add(".log", "text/plain");//識別擴展類型
exten.Mappings.Add(".sln", "text/plain");
exten.Mappings.Add(".lng", "text/plain");
fileServerOptions.StaticFileOptions.ContentTypeProvider = exten;
app.UseFileServer(fileServerOptions);
}
}
