Minor clean-up in Static Files (#17828)

This commit is contained in:
Kahbazi 2019-12-14 00:59:36 +03:30 committed by Chris Ross
parent 49fd4ced63
commit 19d2f6124f
6 changed files with 21 additions and 38 deletions

View File

@ -10,11 +10,5 @@ namespace Microsoft.AspNetCore.StaticFiles
internal const string ServerCapabilitiesKey = "server.Capabilities";
internal const string SendFileVersionKey = "sendfile.Version";
internal const string SendFileVersion = "1.0";
internal const int Status200Ok = 200;
internal const int Status206PartialContent = 206;
internal const int Status304NotModified = 304;
internal const int Status412PreconditionFailed = 412;
internal const int Status416RangeNotSatisfiable = 416;
}
}

View File

@ -63,8 +63,8 @@ namespace Microsoft.AspNetCore.StaticFiles
/// <returns></returns>
public Task Invoke(HttpContext context)
{
if (context.GetEndpoint() == null &&
Helpers.IsGetOrHeadMethod(context.Request.Method)
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);
@ -80,7 +80,7 @@ namespace Microsoft.AspNetCore.StaticFiles
{
// 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) && _options.RedirectToAppendTrailingSlash)
if (_options.RedirectToAppendTrailingSlash && !Helpers.PathEndsInSlash(context.Request.Path))
{
Helpers.RedirectToPathWithSlash(context);
return Task.CompletedTask;

View File

@ -68,7 +68,7 @@ namespace Microsoft.AspNetCore.StaticFiles
_next = next;
_options = options.Value;
_fileProvider = _options.FileProvider ?? Helpers.ResolveFileProvider(hostingEnv);
_formatter = options.Value.Formatter ?? new HtmlDirectoryFormatter(encoder);
_formatter = _options.Formatter ?? new HtmlDirectoryFormatter(encoder);
_matchUrl = _options.RequestPath;
}
@ -80,14 +80,14 @@ namespace Microsoft.AspNetCore.StaticFiles
public Task Invoke(HttpContext context)
{
// Check if the URL matches any expected paths, skip if an endpoint was selected
if (context.GetEndpoint() == null &&
Helpers.IsGetOrHeadMethod(context.Request.Method)
if (context.GetEndpoint() == null
&& Helpers.IsGetOrHeadMethod(context.Request.Method)
&& Helpers.TryMatchPath(context, _matchUrl, forDirectory: true, subpath: out var subpath)
&& TryGetDirectoryInfo(subpath, out var contents))
{
// 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) && _options.RedirectToAppendTrailingSlash)
if (_options.RedirectToAppendTrailingSlash && !Helpers.PathEndsInSlash(context.Request.Path))
{
Helpers.RedirectToPathWithSlash(context);
return Task.CompletedTask;

View File

@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.StaticFiles
{
private const string TextHtmlUtf8 = "text/html; charset=utf-8";
private HtmlEncoder _htmlEncoder;
private readonly HtmlEncoder _htmlEncoder;
/// <summary>
/// Constructs the <see cref="HtmlDirectoryFormatter"/>.

View File

@ -87,9 +87,9 @@ namespace Microsoft.AspNetCore.StaticFiles
}
}
private RequestHeaders RequestHeaders => (_requestHeaders ??= _request.GetTypedHeaders());
private RequestHeaders RequestHeaders => _requestHeaders ??= _request.GetTypedHeaders();
private ResponseHeaders ResponseHeaders => (_responseHeaders ??= _response.GetTypedHeaders());
private ResponseHeaders ResponseHeaders => _responseHeaders ??= _response.GetTypedHeaders();
public bool IsHeadMethod => _requestType.HasFlag(RequestType.IsHead);
@ -149,7 +149,7 @@ namespace Microsoft.AspNetCore.StaticFiles
// 14.24 If-Match
var ifMatch = requestHeaders.IfMatch;
if (ifMatch != null && ifMatch.Any())
if (ifMatch?.Count > 0)
{
_ifMatchState = PreconditionState.PreconditionFailed;
foreach (var etag in ifMatch)
@ -164,7 +164,7 @@ namespace Microsoft.AspNetCore.StaticFiles
// 14.26 If-None-Match
var ifNoneMatch = requestHeaders.IfNoneMatch;
if (ifNoneMatch != null && ifNoneMatch.Any())
if (ifNoneMatch?.Count > 0)
{
_ifNoneMatchState = PreconditionState.ShouldProcess;
foreach (var etag in ifNoneMatch)
@ -260,7 +260,7 @@ namespace Microsoft.AspNetCore.StaticFiles
responseHeaders.ETag = _etag;
responseHeaders.Headers[HeaderNames.AcceptRanges] = "bytes";
}
if (statusCode == Constants.Status200Ok)
if (statusCode == StatusCodes.Status200OK)
{
// this header is only returned here for 200
// it already set to the returned range for 206
@ -304,7 +304,7 @@ namespace Microsoft.AspNetCore.StaticFiles
case PreconditionState.ShouldProcess:
if (IsHeadMethod)
{
await SendStatusAsync(Constants.Status200Ok);
await SendStatusAsync(StatusCodes.Status200OK);
return;
}
@ -328,11 +328,11 @@ namespace Microsoft.AspNetCore.StaticFiles
return;
case PreconditionState.NotModified:
_logger.FileNotModified(SubPath);
await SendStatusAsync(Constants.Status304NotModified);
await SendStatusAsync(StatusCodes.Status304NotModified);
return;
case PreconditionState.PreconditionFailed:
_logger.PreconditionFailed(SubPath);
await SendStatusAsync(Constants.Status412PreconditionFailed);
await SendStatusAsync(StatusCodes.Status412PreconditionFailed);
return;
default:
var exception = new NotImplementedException(GetPreconditionState().ToString());
@ -344,7 +344,7 @@ namespace Microsoft.AspNetCore.StaticFiles
public async Task SendAsync()
{
SetCompressionMode();
ApplyResponseHeaders(Constants.Status200Ok);
ApplyResponseHeaders(StatusCodes.Status200OK);
string physicalPath = _fileInfo.PhysicalPath;
var sendFile = _context.Features.Get<IHttpResponseBodyFeature>();
if (sendFile != null && !string.IsNullOrEmpty(physicalPath))
@ -380,7 +380,7 @@ namespace Microsoft.AspNetCore.StaticFiles
// SHOULD include a Content-Range field with a byte-range-resp-spec of "*". The instance-length specifies
// the current length of the selected resource. e.g. */length
ResponseHeaders.ContentRange = new ContentRangeHeaderValue(_length);
ApplyResponseHeaders(Constants.Status416RangeNotSatisfiable);
ApplyResponseHeaders(StatusCodes.Status416RangeNotSatisfiable);
_logger.RangeNotSatisfiable(SubPath);
return;
@ -389,7 +389,7 @@ namespace Microsoft.AspNetCore.StaticFiles
ResponseHeaders.ContentRange = ComputeContentRange(_range, out var start, out var length);
_response.ContentLength = length;
SetCompressionMode();
ApplyResponseHeaders(Constants.Status206PartialContent);
ApplyResponseHeaders(StatusCodes.Status206PartialContent);
string physicalPath = _fileInfo.PhysicalPath;
var sendFile = _context.Features.Get<IHttpResponseBodyFeature>();

View File

@ -55,7 +55,7 @@ namespace Microsoft.AspNetCore.StaticFiles
_next = next;
_options = options.Value;
_contentTypeProvider = options.Value.ContentTypeProvider ?? new FileExtensionContentTypeProvider();
_contentTypeProvider = _options.ContentTypeProvider ?? new FileExtensionContentTypeProvider();
_fileProvider = _options.FileProvider ?? Helpers.ResolveFileProvider(hostingEnv);
_matchUrl = _options.RequestPath;
_logger = loggerFactory.CreateLogger<StaticFileMiddleware>();
@ -98,18 +98,7 @@ namespace Microsoft.AspNetCore.StaticFiles
private static bool ValidateMethod(HttpContext context)
{
var method = context.Request.Method;
var isValid = false;
if (HttpMethods.IsGet(method))
{
isValid = true;
}
else if (HttpMethods.IsHead(method))
{
isValid = true;
}
return isValid;
return Helpers.IsGetOrHeadMethod(context.Request.Method);
}
internal static bool ValidatePath(HttpContext context, PathString matchUrl, out PathString subPath) => Helpers.TryMatchPath(context, matchUrl, forDirectory: false, out subPath);