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);
}
/// <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; }
}