.net core靜態(tài)中間件的使用
正文
我們使用靜態(tài)文件調(diào)用:
app.UseStaticFiles();
那么這個(gè)默認(rèn)會(huì)將我們根目錄下的wwwroot作為靜態(tài)目錄。
這個(gè)就比較值得注意的,可能剛開(kāi)始學(xué).net core 的小伙伴,會(huì)直接把腳本寫(xiě)在更目錄script這樣是訪問(wèn)不到的。
當(dāng)然了,你可以配置參數(shù)??梢越oUseStaticFiles傳遞參數(shù)。不過(guò)建議不要這么干,因?yàn)檫@是一種默認(rèn)的約定。
在wwwroot下建立一個(gè)index.html,那么訪問(wèn)http://localhost/index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> 靜態(tài)文件 </body> </html>
效果:
如果還有一些其他目錄需要注冊(cè)的話,那么可以這樣:
app.UseStaticFiles(new StaticFileOptions { RequestPath="/files", FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"files")) });
在根目錄建立files:
然后呢,訪問(wèn)就是http://localhost:5000/files/index.html
接下來(lái)介紹一下UseDefaultFiles,這個(gè)是設(shè)置默認(rèn)的文件。
這個(gè)不是說(shuō)404,然后跳轉(zhuǎn)到這個(gè)文件這里哈。
直接看下它的中間件間吧。
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í)很簡(jiǎn)單,將請(qǐng)求轉(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重新請(qǐng)求。
默認(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; } }
有上面這幾個(gè)默認(rèn)的,以此按照順序,當(dāng)然你也可以傳進(jìn)去修改,看下參數(shù)就好。
a目錄建立了一個(gè)index.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> 這是a下面的index.html </body> </html>
那么訪問(wèn)http://localhost:5000/a 就好。
效果:
經(jīng)過(guò)了一次301哈。
那么介紹一下目錄預(yù)覽:
增加服務(wù):
services.AddDirectoryBrowser();
增加中間件:
app.UseDirectoryBrowser();
這樣就可以了。
如果我們前后端像這種不完全分離的情況有一個(gè)問(wèn)題。
比如說(shuō),現(xiàn)在一般3大框架,vue和 angular,react這種的話。你會(huì)發(fā)現(xiàn)一個(gè)問(wèn)題,那就是他們有自己的路由。
這個(gè)時(shí)候可能就會(huì)和我們的路由沖突。
比如說(shuō)http://localhost/pay 需要訪問(wèn)的是index.html。因?yàn)閕ndex.html有自己的路由,顯示pay頁(yè)面。
那么配置路由的時(shí)候應(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開(kāi)頭的,統(tǒng)一定位到index.html,然后再經(jīng)過(guò)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)中間件的資料請(qǐng)關(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 的中間件中返回具體的頁(yè)面的實(shí)現(xiàn)方法
- ASP.NET Core自定義中間件如何讀取Request.Body與Response.Body的內(nèi)容詳解
- .net core webapi通過(guò)中間件獲取請(qǐng)求和響應(yīng)內(nèi)容的方法
- 利用.net core實(shí)現(xiàn)反向代理中間件的方法
- 如何給asp.net core寫(xiě)個(gè)中間件記錄接口耗時(shí)
- ASP.NET Core中間件計(jì)算Http請(qǐng)求時(shí)間示例詳解
- ASP.NET Core應(yīng)用錯(cuò)誤處理之ExceptionHandlerMiddleware中間件呈現(xiàn)“定制化錯(cuò)誤頁(yè)面”
相關(guān)文章
asp.net中使用repeater和PageDataSource搭配實(shí)現(xiàn)分頁(yè)代碼
asp.net中使用repeater和PageDataSource搭配實(shí)現(xiàn)分頁(yè)代碼,需要的朋友可以參考下2013-04-04ASP.NET?Core使用Swagger/OpenAPI規(guī)范
這篇文章介紹了ASP.NET?Core使用Swagger/OpenAPI規(guī)范的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04.net出現(xiàn)80080005錯(cuò)誤的解決辦法分享
這篇文章介紹了.net出現(xiàn)80080005錯(cuò)誤的解決辦法,有需要的朋友可以參考一下,希望可以對(duì)你有所幫助2013-07-07ASP.NET?MVC創(chuàng)建XML文件并實(shí)現(xiàn)元素增刪改
這篇文章介紹了ASP.NET?MVC創(chuàng)建XML文件并實(shí)現(xiàn)元素增刪改的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07jquery.pagination +JSON 動(dòng)態(tài)無(wú)刷新分頁(yè)實(shí)現(xiàn)代碼
jquery.pagination +JSON 動(dòng)態(tài)無(wú)刷新分頁(yè)實(shí)現(xiàn)代碼,需要的朋友可以參考下。2011-12-12