.net core靜態(tài)中間件的使用
正文
我們使用靜態(tài)文件調(diào)用:
app.UseStaticFiles();
那么這個默認(rèn)會將我們根目錄下的wwwroot作為靜態(tài)目錄。
這個就比較值得注意的,可能剛開始學(xué).net core 的小伙伴,會直接把腳本寫在更目錄script這樣是訪問不到的。
當(dāng)然了,你可以配置參數(shù)??梢越oUseStaticFiles傳遞參數(shù)。不過建議不要這么干,因?yàn)檫@是一種默認(rèn)的約定。
在wwwroot下建立一個index.html,那么訪問http://localhost/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
靜態(tài)文件
</body>
</html>
效果:

如果還有一些其他目錄需要注冊的話,那么可以這樣:
app.UseStaticFiles(new StaticFileOptions
{
RequestPath="/files",
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"files"))
});
在根目錄建立files:

然后呢,訪問就是http://localhost:5000/files/index.html
接下來介紹一下UseDefaultFiles,這個是設(shè)置默認(rèn)的文件。
這個不是說404,然后跳轉(zhuǎn)到這個文件這里哈。
直接看下它的中間件間吧。
DefaultFilesMiddleware:
public Task Invoke(HttpContext context)
{
if (context.GetEndpoint() == null &&
Helpers.IsGetOrHeadMethod(context.Request.Method)
&& Helpers.TryMatchPath(context, _matchUrl, forDirectory: true, subpath: out var subpath))
{
var dirContents = _fileProvider.GetDirectoryContents(subpath.Value);
if (dirContents.Exists)
{
// Check if any of our default files exist.
for (int matchIndex = 0; matchIndex < _options.DefaultFileNames.Count; matchIndex++)
{
string defaultFile = _options.DefaultFileNames[matchIndex];
var file = _fileProvider.GetFileInfo(subpath.Value + defaultFile);
// TryMatchPath will make sure subpath always ends with a "/" by adding it if needed.
if (file.Exists)
{
// If the path matches a directory but does not end in a slash, redirect to add the slash.
// This prevents relative links from breaking.
if (!Helpers.PathEndsInSlash(context.Request.Path))
{
context.Response.StatusCode = StatusCodes.Status301MovedPermanently;
var request = context.Request;
var redirect = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path + "/", request.QueryString);
context.Response.Headers[HeaderNames.Location] = redirect;
return Task.CompletedTask;
}
// Match found, re-write the url. A later middleware will actually serve the file.
context.Request.Path = new PathString(context.Request.Path.Value + defaultFile);
break;
}
}
}
}
return _next(context);
}
里面做的事情其實(shí)很簡單,將請求轉(zhuǎn)換為文件路徑。分為末尾是/和末尾不是/的。
比如http://localhost/a/,那么轉(zhuǎn)換為wwwroot/a/路徑。然后判斷context.Request.Path末尾是否是/,如果是那么給文件路徑加上index.html或者其他默認(rèn)文件。如果判斷存在的話,那么返回文件。
比如http://localhost/a,那么轉(zhuǎn)換為wwwroot/a/路徑。然后判斷context.Request.Path末尾是不是/,如果是那么給文件路徑加上index.html或者其他默認(rèn)文件。如果判斷存在的話,那么給路徑加上/,然后返回301重新請求。
默認(rèn)的在DefaultFilesOptions:
/// <summary>
/// Options for selecting default file names.
/// </summary>
public class DefaultFilesOptions : SharedOptionsBase
{
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
public DefaultFilesOptions()
: this(new SharedOptions())
{
}
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
/// <param name="sharedOptions"></param>
public DefaultFilesOptions(SharedOptions sharedOptions)
: base(sharedOptions)
{
// Prioritized list
DefaultFileNames = new List<string>
{
"default.htm",
"default.html",
"index.htm",
"index.html",
};
}
/// <summary>
/// An ordered list of file names to select by default. List length and ordering may affect performance.
/// </summary>
public IList<string> DefaultFileNames { get; set; }
}
有上面這幾個默認(rèn)的,以此按照順序,當(dāng)然你也可以傳進(jìn)去修改,看下參數(shù)就好。

a目錄建立了一個index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
這是a下面的index.html
</body>
</html>
那么訪問http://localhost:5000/a 就好。
效果:


經(jīng)過了一次301哈。
那么介紹一下目錄預(yù)覽:
增加服務(wù):
services.AddDirectoryBrowser();
增加中間件:
app.UseDirectoryBrowser();

這樣就可以了。
如果我們前后端像這種不完全分離的情況有一個問題。
比如說,現(xiàn)在一般3大框架,vue和 angular,react這種的話。你會發(fā)現(xiàn)一個問題,那就是他們有自己的路由。
這個時候可能就會和我們的路由沖突。
比如說http://localhost/pay 需要訪問的是index.html。因?yàn)閕ndex.html有自己的路由,顯示pay頁面。
那么配置路由的時候應(yīng)該加一條。
app.MapWhen(context =>
{
return !context.Request.Path.Value.StartsWith("/api");
}, builder =>
{
var option = new RewriteOptions();
option.AddRewrite(".*","/index.html",true);
app.UseRewriter(option);
app.UseStaticFiles();
});
就是如果不是/api開頭的,統(tǒng)一定位到index.html,然后再經(jīng)過UseStaticFiles處理,就直接到了index.html。
RewriteOptions這些轉(zhuǎn)換在細(xì)節(jié)篇中介紹。當(dāng)然你也可以直接去給HttpContext body注入index.html流,然后返回,但是這樣用不到一些其他特性,就不介紹了。
結(jié)
以上就是.net core靜態(tài)中間件的使用的詳細(xì)內(nèi)容,更多關(guān)于.net core靜態(tài)中間件的資料請關(guān)注腳本之家其它相關(guān)文章!
- ASP.NET Core 應(yīng)用程序中的靜態(tài)文件中間件的實(shí)現(xiàn)
- .Net Core中間件之靜態(tài)文件(StaticFiles)示例詳解
- .net core異常中間件的使用
- ASP.NET Core中間件初始化的實(shí)現(xiàn)
- 詳解ASP.NET Core 中基于工廠的中間件激活的實(shí)現(xiàn)方法
- 在 asp.net core 的中間件中返回具體的頁面的實(shí)現(xiàn)方法
- ASP.NET Core自定義中間件如何讀取Request.Body與Response.Body的內(nèi)容詳解
- .net core webapi通過中間件獲取請求和響應(yīng)內(nèi)容的方法
- 利用.net core實(shí)現(xiàn)反向代理中間件的方法
- 如何給asp.net core寫個中間件記錄接口耗時
- ASP.NET Core中間件計算Http請求時間示例詳解
- ASP.NET Core應(yīng)用錯誤處理之ExceptionHandlerMiddleware中間件呈現(xiàn)“定制化錯誤頁面”
相關(guān)文章
.NET 6開發(fā)TodoList應(yīng)用之實(shí)現(xiàn)查詢排序
這篇文章主要介紹了如何通過.NET 6實(shí)現(xiàn)查詢排序功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí).NET 6有一定的幫助,感興趣的同學(xué)可以了解一下2022-01-01
ASP.NET使用xslt將xml轉(zhuǎn)換成Excel
本文介紹利用Excel軟件生成格式,提取和精簡之后制作成xslt文件,將xml導(dǎo)入,以xslt為模板,生成新的Excel文件的過程。2016-05-05
動態(tài)加載Js代碼到Head標(biāo)簽中的腳本
我遇到了這樣的問題,請教google,結(jié)果大多數(shù)只是介紹那個注冊js的幾個函數(shù),而這幾個函數(shù)插入的js都在body里面,幸而在老外那里看到了這個代碼,其實(shí)比較簡單,但夠有用2009-01-01
.NET?Framework?的項(xiàng)目如何使用?FTP?下載文件
本文專門針對面向?.NET?Framework?的項(xiàng)目,?對于面向?.NET?6?及更高版本的項(xiàng)目,不再支持?FTP,此示例演示如何從?FTP?服務(wù)器下載文件,感興趣的朋友跟隨小編一起看看吧2024-01-01
在ASP.NET中實(shí)現(xiàn)彈出日歷的具體方法
這篇文章介紹了ASP.NET彈出日歷功能的實(shí)現(xiàn)方法,有需要的朋友可以參考一下2013-07-07
使用ASP.NET創(chuàng)建線程實(shí)例教程
這篇文章主要介紹了使用ASP.NET創(chuàng)建線程的方法,需要的朋友可以參考下2014-07-07

