Fixes problem with #7530 where UmbracoContext is empty when HtmlImageSourceParser gets initialized

This commit is contained in:
Sebastiaan Janssen
2020-02-06 15:10:05 +01:00
parent 45e4e39412
commit fbd95f1c8e

View File

@@ -13,14 +13,10 @@ namespace Umbraco.Web.Templates
this._getMediaUrl = getMediaUrl; this._getMediaUrl = getMediaUrl;
} }
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
public HtmlImageSourceParser(IUmbracoContextAccessor umbracoContextAccessor) public HtmlImageSourceParser(IUmbracoContextAccessor umbracoContextAccessor)
{ {
if (umbracoContextAccessor?.UmbracoContext?.UrlProvider == null) _umbracoContextAccessor = umbracoContextAccessor;
{
return;
}
_getMediaUrl = (guid) => umbracoContextAccessor.UmbracoContext.UrlProvider.GetMediaUrl(guid);
} }
private static readonly Regex ResolveImgPattern = new Regex(@"(<img[^>]*src="")([^""\?]*)((?:\?[^""]*)?""[^>]*data-udi="")([^""]*)(""[^>]*>)", private static readonly Regex ResolveImgPattern = new Regex(@"(<img[^>]*src="")([^""\?]*)((?:\?[^""]*)?""[^>]*data-udi="")([^""]*)(""[^>]*>)",
@@ -29,7 +25,7 @@ namespace Umbraco.Web.Templates
private static readonly Regex DataUdiAttributeRegex = new Regex(@"data-udi=\\?(?:""|')(?<udi>umb://[A-z0-9\-]+/[A-z0-9]+)\\?(?:""|')", private static readonly Regex DataUdiAttributeRegex = new Regex(@"data-udi=\\?(?:""|')(?<udi>umb://[A-z0-9\-]+/[A-z0-9]+)\\?(?:""|')",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private readonly Func<Guid, string> _getMediaUrl; private Func<Guid, string> _getMediaUrl;
/// <summary> /// <summary>
/// Parses out media UDIs from an html string based on 'data-udi' html attributes /// Parses out media UDIs from an html string based on 'data-udi' html attributes
@@ -57,12 +53,11 @@ namespace Umbraco.Web.Templates
/// <remarks>Umbraco image tags are identified by their data-udi attributes</remarks> /// <remarks>Umbraco image tags are identified by their data-udi attributes</remarks>
public string EnsureImageSources(string text) public string EnsureImageSources(string text)
{ {
// no point in doing any processing if we don't have if (_umbracoContextAccessor.UmbracoContext == null)
// a function to retrieve Urls throw new InvalidOperationException("Could not parse image sources, there is no current UmbracoContext");
if (_getMediaUrl == null)
{ if(_getMediaUrl == null)
return text; _getMediaUrl = (guid) => _umbracoContextAccessor.UmbracoContext.UrlProvider.GetMediaUrl(guid);
}
return ResolveImgPattern.Replace(text, match => return ResolveImgPattern.Replace(text, match =>
{ {