added ETag / 304 Not Modified logic to File server for performance optimization

This commit is contained in:
Shaun Walker 2022-10-29 10:23:04 -04:00
parent 40ddbbfbb7
commit 23d1dd23d1

View File

@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Net.Http.Headers;
using Oqtane.Enums;
using Oqtane.Extensions;
using Oqtane.Infrastructure;
@ -73,6 +74,17 @@ namespace Oqtane.Pages
if (file != null)
{
if (file.Folder.SiteId == _alias.SiteId && _userPermissions.IsAuthorized(User, PermissionNames.View, file.Folder.Permissions))
{
// calculate ETag using last modified date and file size
var etag = Convert.ToString(file.ModifiedOn.Ticks ^ file.Size, 16);
var header = "";
if (HttpContext.Request.Headers.ContainsKey(HeaderNames.IfNoneMatch))
{
header = HttpContext.Request.Headers[HeaderNames.IfNoneMatch].ToString();
}
if (!header.Equals(etag))
{
var filepath = _files.GetFilePath(file);
if (System.IO.File.Exists(filepath))
@ -84,6 +96,7 @@ namespace Oqtane.Pages
}
else
{
HttpContext.Response.Headers.Add(HeaderNames.ETag, etag);
return PhysicalFile(filepath, file.GetMimeType());
}
}
@ -94,6 +107,12 @@ namespace Oqtane.Pages
}
}
else
{
HttpContext.Response.StatusCode = (int)HttpStatusCode.NotModified;
return Content(String.Empty);
}
}
else
{
_logger.Log(LogLevel.Error, this, LogFunction.Security, "Unauthorized File Access Attempt {SiteId} {Path}", _alias.SiteId, path);
HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;