Files
Umbraco-CMS/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs

182 lines
6.7 KiB
C#
Raw Normal View History

2020-12-08 16:33:50 +11:00
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
using Umbraco.Core.Cache;
2020-12-08 16:33:50 +11:00
using Umbraco.Core.Logging;
using Umbraco.Web.Common.Lifetime;
using Umbraco.Web.PublishedCache.NuCache;
namespace Umbraco.Web.Common.Middleware
{
/// <summary>
/// Manages Umbraco request objects and their lifetime
/// </summary>
/// <remarks>
/// <para>
/// This is responsible for initializing the content cache
/// </para>
/// <para>
/// This is responsible for creating and assigning an <see cref="IUmbracoContext"/>
/// </para>
/// </remarks>
public class UmbracoRequestMiddleware : IMiddleware
{
2020-09-28 08:26:21 +02:00
private readonly ILogger<UmbracoRequestMiddleware> _logger;
private readonly IUmbracoRequestLifetimeManager _umbracoRequestLifetimeManager;
private readonly IUmbracoContextFactory _umbracoContextFactory;
private readonly IRequestCache _requestCache;
private readonly IBackOfficeSecurityFactory _backofficeSecurityFactory;
private readonly PublishedSnapshotServiceEventHandler _publishedSnapshotServiceEventHandler;
private static bool s_cacheInitialized = false;
private static bool s_cacheInitializedFlag = false;
private static object s_cacheInitializedLock = new object();
2020-12-08 16:33:50 +11:00
/// <summary>
/// Initializes a new instance of the <see cref="UmbracoRequestMiddleware"/> class.
/// </summary>
public UmbracoRequestMiddleware(
2020-09-28 08:26:21 +02:00
ILogger<UmbracoRequestMiddleware> logger,
IUmbracoRequestLifetimeManager umbracoRequestLifetimeManager,
IUmbracoContextFactory umbracoContextFactory,
IRequestCache requestCache,
IBackOfficeSecurityFactory backofficeSecurityFactory,
PublishedSnapshotServiceEventHandler publishedSnapshotServiceEventHandler)
{
_logger = logger;
_umbracoRequestLifetimeManager = umbracoRequestLifetimeManager;
_umbracoContextFactory = umbracoContextFactory;
_requestCache = requestCache;
_backofficeSecurityFactory = backofficeSecurityFactory;
_publishedSnapshotServiceEventHandler = publishedSnapshotServiceEventHandler;
}
2020-12-08 16:33:50 +11:00
/// <inheritdoc/>
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var requestUri = new Uri(context.Request.GetEncodedUrl(), UriKind.RelativeOrAbsolute);
// do not process if client-side request
if (requestUri.IsClientSideRequest())
{
await next(context);
return;
}
EnsureContentCacheInitialized();
_backofficeSecurityFactory.EnsureBackOfficeSecurity(); // Needs to be before UmbracoContext, TODO: Why?
2020-12-08 16:33:50 +11:00
UmbracoContextReference umbracoContextReference = _umbracoContextFactory.EnsureUmbracoContext();
bool isFrontEndRequest = umbracoContextReference.UmbracoContext.IsFrontEndUmbracoRequest();
try
{
if (isFrontEndRequest)
{
2020-12-08 16:33:50 +11:00
LogHttpRequest.TryGetCurrentHttpRequestId(out Guid httpRequestId, _requestCache);
_logger.LogTrace("Begin request [{HttpRequestId}]: {RequestUrl}", httpRequestId, requestUri);
}
try
{
_umbracoRequestLifetimeManager.InitRequest(context);
}
catch (Exception ex)
{
// try catch so we don't kill everything in all requests
_logger.LogError(ex.Message);
}
finally
{
try
{
await next(context);
}
finally
{
_umbracoRequestLifetimeManager.EndRequest(context);
}
}
}
finally
{
if (isFrontEndRequest)
{
LogHttpRequest.TryGetCurrentHttpRequestId(out var httpRequestId, _requestCache);
_logger.LogTrace("End Request [{HttpRequestId}]: {RequestUrl} ({RequestDuration}ms)", httpRequestId, requestUri, DateTime.Now.Subtract(umbracoContextReference.UmbracoContext.ObjectCreated).TotalMilliseconds);
}
try
{
DisposeRequestCacheItems(_logger, _requestCache, requestUri);
}
finally
{
umbracoContextReference.Dispose();
}
}
}
/// <summary>
/// Any object that is in the HttpContext.Items collection that is IDisposable will get disposed on the end of the request
/// </summary>
2020-09-28 08:26:21 +02:00
private static void DisposeRequestCacheItems(ILogger<UmbracoRequestMiddleware> logger, IRequestCache requestCache, Uri requestUri)
{
// do not process if client-side request
if (requestUri.IsClientSideRequest())
{
return;
}
// get a list of keys to dispose
var keys = new HashSet<string>();
foreach (var i in requestCache)
{
if (i.Value is IDisposeOnRequestEnd || i.Key is IDisposeOnRequestEnd)
{
keys.Add(i.Key);
}
}
// dispose each item and key that was found as disposable.
foreach (var k in keys)
{
try
{
requestCache.Get(k).DisposeIfDisposable();
}
catch (Exception ex)
{
logger.LogError("Could not dispose item with key " + k, ex);
}
try
{
k.DisposeIfDisposable();
}
catch (Exception ex)
{
logger.LogError("Could not dispose item key " + k, ex);
}
}
}
/// <summary>
/// Initializes the content cache one time
/// </summary>
private void EnsureContentCacheInitialized() => LazyInitializer.EnsureInitialized(
ref s_cacheInitialized,
ref s_cacheInitializedFlag,
ref s_cacheInitializedLock,
() =>
{
_publishedSnapshotServiceEventHandler.Initialize();
return true;
});
}
}