asp .net core靜態(tài)文件資源的深入講解
前言
對(duì)靜態(tài)資源的簡(jiǎn)單的一個(gè)概況,在《重新整理.net core 計(jì)1400篇》系列后面會(huì)深入。
正文
我們?cè)诩尤胫虚g件是這樣寫(xiě)的:
app.UseStaticFiles();
默認(rèn)是給wwwroot提供資源。
那么我訪問(wèn)https://localhost:44330/js/site.js 資源,就可以訪問(wèn)到。
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification // for details on configuring this project to bundle and minify static web assets. // Write your JavaScript code.
同樣我們可以自定義路徑。
app.UseStaticFiles(new StaticFileOptions {
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Static")),
RequestPath="/static"
});
上面在根目錄下的static建立路由,路由路徑static 為標(biāo)識(shí)。
訪問(wèn):
https://localhost:44330/static/images/index.jpg
就能看到一張圖片了。
同樣再次訪問(wèn),https://localhost:44330/js/site.js 依然可以訪問(wèn),看了這個(gè)wwwroot 是一個(gè)釘子戶(hù),無(wú)論如何添加還是存在的。
const string cacheMaxAge = "60480";
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions {
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Static")),
RequestPath="/static",
OnPrepareResponse = ctx => {
ctx.Context.Response.Headers.Append("cache-control", $"public,max-age={cacheMaxAge}");
}
}
);
可以設(shè)置一些緩存。

靜態(tài)文件授權(quán)
官方倒是提供了兩種方法。
一種是,讓靜態(tài)文件路由放到權(quán)限之后。
app.UseAuthentication();
app.UseAuthorization();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "Static")),
RequestPath = "/static"
});
另一種比較自定義高:
[Authorize]
public IActionResult BannerImage()
{
var filePath = Path.Combine(
_env.ContentRootPath, "MyStaticFiles", "images", "red-rose.jpg");
return PhysicalFile(filePath, "image/jpeg");
}
可以根據(jù)參數(shù)做一些邏輯變化。
但是這些方式比較影響性能,一般來(lái)說(shuō)靜態(tài)文件是開(kāi)放的,而用戶(hù)上傳的文件是通過(guò)加密的,放在存儲(chǔ)服務(wù)器上。
當(dāng)然小型項(xiàng)目,可以用用。
靜態(tài)文件目錄
Configure中添加:
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider=new PhysicalFileProvider(Path.Combine(env.ContentRootPath,"Static")),
RequestPath="/static"
});
這個(gè)中間件注入的位置是應(yīng)該在UseRouting之前的,同樣是性能問(wèn)題。
然后在ConfigureServices中添加:
services.AddDirectoryBrowser();
效果:

這種方式呢,一般只是在dev環(huán)境下打開(kāi),真正的生產(chǎn)環(huán)境由于安全問(wèn)題就不打開(kāi)的。
默認(rèn)文檔
app.UseDefaultFiles(); app.UseStaticFiles();
app.UseStaticFiles(); 才是真正的路由。
app.UseDefaultFiles(); 只是說(shuō)提供一些參數(shù),比如配置下面這些為默認(rèn)項(xiàng)。
default.htm default.html index.htm index.html
其實(shí)是這樣一個(gè)過(guò)程,app.UseStaticFiles() 如果沒(méi)有找到相應(yīng)的路由,那么應(yīng)該給下一個(gè)中間件。
如果調(diào)用了app.UseDefaultFiles(),那么會(huì)去找是否存在默認(rèn)項(xiàng),默認(rèn)是去wwwroot 下尋找上述的默認(rèn)項(xiàng)。
默認(rèn)文檔可以進(jìn)行修改:
var options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mydefault.html");
app.UseDefaultFiles(options);
app.UseStaticFiles();
UseFileServer 結(jié)合了 UseStaticFiles、UseDefaultFiles 和 UseDirectoryBrowser(可選)的功能。
app.UseFileServer(enableDirectoryBrowsing: true);
enableDirectoryBrowsing 表示是否使用UseDirectoryBrowser。
FileExtensionContentTypeProvider
FileExtensionContentTypeProvider 類(lèi)包含 Mappings 屬性,用作文件擴(kuò)展名到 MIME 內(nèi)容類(lèi)型的映射。
比如說(shuō)我去訪問(wèn):https://localhost:44330/static/test.myapp
我在static 下有test.mapp 這個(gè)文件,但是靜態(tài)文件處理并沒(méi)有去處理。
原因:

客服端發(fā)了這樣一個(gè)請(qǐng)求,人家接受這些流,但是服務(wù)器找到到,myapp 對(duì)應(yīng)的媒體類(lèi)型,那么這個(gè)時(shí)候客戶(hù)端就不會(huì)接受了,服務(wù)端也認(rèn)為沒(méi)有找到。
官方給了例子:
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.UseDefaultFiles();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Static")),
RequestPath = "/static",
OnPrepareResponse = ctx => {
ctx.Context.Response.Headers.Append("cache-control", $"public,max-age={cacheMaxAge}");
},
ContentTypeProvider= provider
}
給他加一個(gè)媒體類(lèi)型,認(rèn)為myapp 應(yīng)該是一個(gè)需要下載文件。
然后運(yùn)行之,然后就會(huì)出現(xiàn)下載。
同樣,我們寫(xiě)的是.html,如果我們不喜歡可以去寫(xiě).htm3也行。
https://localhost:44330/static/index.htm3
結(jié)果:

因?yàn)?code>provider.Mappings[".htm3"] = "text/html"; ,.htm3被映射成了text/html,那么客戶(hù)端就按照這種格式處理。所以模板引擎就可以多樣性,有興趣自己也可以去設(shè)計(jì)。
這就是媒體類(lèi)型映射。
如果是媒體類(lèi)型未知的情況下,那么可以這樣:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Static")),
RequestPath = "/static",
OnPrepareResponse = ctx => {
ctx.Context.Response.Headers.Append("cache-control", $"public,max-age={cacheMaxAge}");
},
ServeUnknownFileTypes = true,
DefaultContentType = "image/png"
}
);
ServeUnknownFileTypes true
DefaultContentType "image/png" 讓客戶(hù)端按照?qǐng)D片處理。

但是官方給了建議。
啟用 ServeUnknownFileTypes 會(huì)形成安全隱患。 它默認(rèn)處于禁用狀態(tài),不建議使用。
FileExtensionContentTypeProvider 提供了更安全的替代方法來(lái)提供含非標(biāo)準(zhǔn)擴(kuò)展名的文件。
總結(jié)
到此這篇關(guān)于asp .net core靜態(tài)文件資源的文章就介紹到這了,更多相關(guān)asp .net core靜態(tài)文件資源內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
asp.net 編譯器錯(cuò)誤信息: CS0006: 未能找到元數(shù)據(jù)文件 該死的.NET
今天公司新上一臺(tái)志強(qiáng)虛擬主機(jī) 所有配置都好了 給客戶(hù)調(diào)整.net 出現(xiàn)了報(bào)錯(cuò)2009-06-06
.NET?Core項(xiàng)目使用swagger開(kāi)發(fā)組件
這篇文章介紹了.NET?Core項(xiàng)目使用swagger開(kāi)發(fā)組件的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
給Repeater控件里添加序號(hào)的5種才常見(jiàn)方法介紹
Repeater是我們經(jīng)常用的一個(gè)顯示數(shù)據(jù)集的數(shù)據(jù)控件那么我們?cè)撛趺礊镽epeater控件添加序號(hào)呢?下面編輯為大家介紹幾種常用的為Repeater控件添加序號(hào)的方法2013-09-09
iis中為每個(gè)應(yīng)用程序池單獨(dú)設(shè)置aspnet.config配置文件
ASP.NET2.0之后的版本就在各Framework的根目錄下提供了一個(gè)aspnet.config文件,這個(gè)文件用來(lái)配置全局的一些信息,但是一直以來(lái)我們都沒(méi)有怎么用過(guò)2011-12-12
asp.net正則表達(dá)式刪除指定的HTML標(biāo)簽的代碼
抓取某網(wǎng)頁(yè)的數(shù)據(jù)后(比如描述),如果照原樣顯示的話,可能會(huì)因?yàn)樗锩姘瑳](méi)有閉合的HTML標(biāo)簽而打亂了格式,也可能它里面用了比較讓人 費(fèi)解 的HTML標(biāo)簽,把預(yù)訂的格式攪亂.2010-09-09

