1: public class DefaultFilesMiddleware
2: {
3: private RequestDelegate _next;
4: private DefaultFilesOptions _options;
5:
6: public DefaultFilesMiddleware(RequestDelegate next, IHostingEnvironment env, IOptions<DefaultFilesOptions> options)
7: {
8: _next = next;
9: _options = options.Value;
10: _options.FileProvider = _options.FileProvider ?? env.WebRootFileProvider;
11: }
12:
13: public async Task Invoke(HttpContext context)
14: {
15: //只处理GET和HEAD请求
16: if (!new string[] { "GET", "HEAD" }.Contains(context.Request.Method,StringComparer.OrdinalIgnoreCase))
17: {
18: await _next(context);
19: return;
20: }
21:
22: //检验当前路径是否与注册的请求路径相匹配
23: PathString path = new PathString(context.Request.Path.Value.TrimEnd('/') + "/");
24: PathString subpath;
25: if (!path.StartsWithSegments(_options.RequestPath, out subpath))
26: {
27: await _next(context);
28: return;
29: }
30:
31: //检验目标目录是否存在
32: if (!_options.FileProvider.GetDirectoryContents(subpath).Exists)
33: {
34: await _next(context);
35: return;
36: }
37:
38: //检验当前目录是否包含默认文件
39: foreach (var fileName in _options.DefaultFileNames)
40: {
41: if (_options.FileProvider.GetFileInfo($"{subpath}{fileName}").Exists)
42: {
43: //如果当前路径不以"/"作为后缀,会响应一个针对“标准”URL的重定向
44: if (!context.Request.Path.Value.EndsWith("/"))
45: {
46: context.Response.StatusCode = 302;
47: context.Response.GetTypedHeaders().Location = new Uri(path.Value + context.Request.QueryString);
48: return;
49: }
50: //将针对目录的URL更新为针对默认文件的URL
51:
52: }
53: }
54: await _next(context);
55: }
56: }