溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

.net core靜態(tài)中間件有什么作用

發(fā)布時間:2021-06-16 13:37:17 來源:億速云 閱讀:213 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“.net core靜態(tài)中間件有什么作用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“.net core靜態(tài)中間件有什么作用”吧!

正文

我們使用靜態(tài)文件調(diào)用:

app.UseStaticFiles();

那么這個默認會將我們根目錄下的wwwroot作為靜態(tài)目錄。

這個就比較值得注意的,可能剛開始學(xué).net core 的小伙伴,會直接把腳本寫在更目錄script這樣是訪問不到的。

當(dāng)然了,你可以配置參數(shù)。可以給UseStaticFiles傳遞參數(shù)。不過建議不要這么干,因為這是一種默認的約定。

在wwwroot下建立一個index.html,那么訪問http://localhost/index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    靜態(tài)文件
</body>
</html>

效果:

.net core靜態(tài)中間件有什么作用

如果還有一些其他目錄需要注冊的話,那么可以這樣:

app.UseStaticFiles(new StaticFileOptions
{
	RequestPath="/files",
	FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"files"))
});

在根目錄建立files:

.net core靜態(tài)中間件有什么作用

然后呢,訪問就是http://localhost:5000/files/index.html

接下來介紹一下UseDefaultFiles,這個是設(shè)置默認的文件。

這個不是說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或者其他默認文件。如果判斷存在的話,那么返回文件。

比如http://localhost/a,那么轉(zhuǎn)換為wwwroot/a/路徑。然后判斷context.Request.Path末尾是不是/,如果是那么給文件路徑加上index.html或者其他默認文件。如果判斷存在的話,那么給路徑加上/,然后返回301重新請求。

默認的在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; }
}

有上面這幾個默認的,以此按照順序,當(dāng)然你也可以傳進去修改,看下參數(shù)就好。

.net core靜態(tài)中間件有什么作用

a目錄建立了一個index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    這是a下面的index.html
</body>
</html>

那么訪問http://localhost:5000/a 就好。

效果:

.net core靜態(tài)中間件有什么作用

.net core靜態(tài)中間件有什么作用

經(jīng)過了一次301哈。

那么介紹一下目錄預(yù)覽:

增加服務(wù):

services.AddDirectoryBrowser();

增加中間件:

app.UseDirectoryBrowser();

.net core靜態(tài)中間件有什么作用

這樣就可以了。

如果我們前后端像這種不完全分離的情況有一個問題。

比如說,現(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)換在細節(jié)篇中介紹。當(dāng)然你也可以直接去給HttpContext body注入index.html流,然后返回,但是這樣用不到一些其他特性,就不介紹了。

到此,相信大家對“.net core靜態(tài)中間件有什么作用”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI