---
title: .NET COER 專案架IIS上使用瀏覽目錄方式下載檔案
tags: .NET COER,IIS,open
description: .NET COER 瀏覽目錄方式下載檔案
---
> [name=Jiesen] [time=20210809 ] [color=#907bf7]
[TOC]
# 前言
==專案架在IIS上要能夠用URL方式下載站台上某個資料夾內的檔案,這個範列使用的是API專案==


---
# 相關設定
## IIS 站台瀏覽目錄之設定
==到IIS上將瀏覽目錄啟動就OK==
==此功能沒做就算程式有設定也無法瀏覽資料夾或下在檔案==

---
## .NET COER 官方程式設定範列
:::spoiler {state="open"} 微軟的範列
==在Startup.cs內的Configure中做設定==
## 添加可使用的附檔名及設定Content-Type的局部程式碼
有些不常用的附檔名要特別添加不然無法下載檔案
```C#
// Set up custom content types - associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";//添加可使用的附檔名,設定Content-Type
```
### 設定++檔案下載++及++瀏覽資料夾內容++之權限局部程式碼
==有開++下載權限++但沒有++開瀏覽權限++,這樣可以下載檔案但不能瀏覽資料夾內容==
==如要下在檔案需要知道該資料夾下有什麼檔案直接下URL抓取如下==
==http://192.xxx.0.xx:81/MyImages/xxx.txt==
```C#
//開啟下載檔案權限
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
//env.WebRootPath=取得網站根目錄
Path.Combine(env.WebRootPath, "要授權的資料夾名稱")),
//http://192.xxx.0.xx:81/MyImages/
RequestPath = "/MyImages",//設定URL名稱
ContentTypeProvider = provider//添加可使用的附檔名
});
//開啟瀏覽資料夾內容的權限
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.WebRootPath, "images")),
RequestPath = "/MyImages"
});
```
下面程式碼是++添加副檔名++跟++瀏覽資料夾權限++及++下載權限++完整範列
```C#
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
// using Microsoft.AspNetCore.StaticFiles;
// using Microsoft.Extensions.FileProviders;
// using System.IO;
// Set up custom content types - associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4");
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.WebRootPath, "images")),
RequestPath = "/MyImages",
ContentTypeProvider = provider
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.WebRootPath, "images")),
RequestPath = "/MyImages"
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
```
# 參考網站
[IT幫幫忙參考](https://ithelp.ithome.com.tw/articles/10193208)
[微軟官方網站](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-5.0#static-file-authorization
)
:::