.net core靜態(tài)中間件的使用
正文
我們使用靜態(tài)文件調(diào)用:
app.UseStaticFiles();
那么這個默認(rèn)會將我們根目錄下的wwwroot作為靜態(tài)目錄。
這個就比較值得注意的,可能剛開始學(xué).net core 的小伙伴,會直接把腳本寫在更目錄script這樣是訪問不到的。
當(dāng)然了,你可以配置參數(shù)??梢越oUseStaticFiles傳遞參數(shù)。不過建議不要這么干,因為這是一種默認(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);
}
里面做的事情其實很簡單,將請求轉(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。因為index.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)文件中間件的實現(xiàn)
- .Net Core中間件之靜態(tài)文件(StaticFiles)示例詳解
- .net core異常中間件的使用
- ASP.NET Core中間件初始化的實現(xiàn)
- 詳解ASP.NET Core 中基于工廠的中間件激活的實現(xiàn)方法
- 在 asp.net core 的中間件中返回具體的頁面的實現(xiàn)方法
- ASP.NET Core自定義中間件如何讀取Request.Body與Response.Body的內(nèi)容詳解
- .net core webapi通過中間件獲取請求和響應(yīng)內(nèi)容的方法
- 利用.net core實現(xiàn)反向代理中間件的方法
- 如何給asp.net core寫個中間件記錄接口耗時
- ASP.NET Core中間件計算Http請求時間示例詳解
- ASP.NET Core應(yīng)用錯誤處理之ExceptionHandlerMiddleware中間件呈現(xiàn)“定制化錯誤頁面”
相關(guān)文章
asp.net中使用repeater和PageDataSource搭配實現(xiàn)分頁代碼
asp.net中使用repeater和PageDataSource搭配實現(xiàn)分頁代碼,需要的朋友可以參考下2013-04-04
ASP.NET?Core使用Swagger/OpenAPI規(guī)范
這篇文章介紹了ASP.NET?Core使用Swagger/OpenAPI規(guī)范的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
ASP.NET?MVC創(chuàng)建XML文件并實現(xiàn)元素增刪改
這篇文章介紹了ASP.NET?MVC創(chuàng)建XML文件并實現(xiàn)元素增刪改的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07
jquery.pagination +JSON 動態(tài)無刷新分頁實現(xiàn)代碼
jquery.pagination +JSON 動態(tài)無刷新分頁實現(xiàn)代碼,需要的朋友可以參考下。2011-12-12

