目录

正文

我们使用静态文件调用:

app.usestaticfiles();

那么这个默认会将我们根目录下的wwwroot作为静态目录。

这个就比较值得注意的,可能刚开始学.net core 的小伙伴,会直接把脚本写在更目录script这样是访问不到的。

当然了,你可以配置参数。可以给usestaticfiles传递参数。不过建议不要这么干,因为这是一种默认的约定。

在wwwroot下建立一个index.html,那么访问http://localhost/index.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    静态文件
</body>
</html>

效果:

如果还有一些其他目录需要注册的话,那么可以这样:

app.usestaticfiles(new staticfileoptions
{
	requestpath="/files",
	fileprovider = new physicalfileprovider(path.combine(directory.getcurrentdirectory(),"files"))
});

在根目录建立files:

然后呢,访问就是http://localhost:5000/files/index.html

接下来介绍一下usedefaultfiles,这个是设置默认的文件。

这个不是说404,然后跳转到这个文件这里哈。

直接看下它的中间件间吧。
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);
}

里面做的事情其实很简单,将请求转换为文件路径。分为末尾是/和末尾不是/的。

比如http://localhost/a/,那么转换为wwwroot/a/路径。然后判断context.request.path末尾是否是/,如果是那么给文件路径加上index.html或者其他默认文件。如果判断存在的话,那么返回文件。

比如http://localhost/a,那么转换为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; }
}

有上面这几个默认的,以此按照顺序,当然你也可以传进去修改,看下参数就好。

a目录建立了一个index.html:

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

那么访问http://localhost:5000/a 就好。

效果:

经过了一次301哈。

那么介绍一下目录预览:

增加服务:

services.adddirectorybrowser();

增加中间件:

app.usedirectorybrowser();

这样就可以了。

如果我们前后端像这种不完全分离的情况有一个问题。

比如说,现在一般3大框架,vue和 angular,react这种的话。你会发现一个问题,那就是他们有自己的路由。

这个时候可能就会和我们的路由冲突。

比如说 需要访问的是index.html。因为index.html有自己的路由,显示pay页面。

那么配置路由的时候应该加一条。

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开头的,统一定位到index.html,然后再经过usestaticfiles处理,就直接到了index.html。

rewriteoptions这些转换在细节篇中介绍。当然你也可以直接去给httpcontext body注入index.html流,然后返回,但是这样用不到一些其他特性,就不介绍了。

以上就是.net core静态中间件的使用的详细内容,更多关于.net core静态中间件的资料请关注www.887551.com其它相关文章!