Skip to content

Instantly share code, notes, and snippets.

@deMD
Created December 17, 2019 10:38
Show Gist options
  • Save deMD/3937354d7c8285464a04aafa13a99d10 to your computer and use it in GitHub Desktop.
Save deMD/3937354d7c8285464a04aafa13a99d10 to your computer and use it in GitHub Desktop.
Umbraco CdnMediaUrlProvider
public class CdnMediaUrlProvider : IMediaUrlProvider
{
public virtual UrlInfo GetMediaUrl(
UmbracoContext umbracoContext,
IPublishedContent content,
string propertyAlias,
UrlMode mode,
string culture,
Uri current)
{
var prop = content.GetProperty(propertyAlias);
var value = prop?.GetValue(culture);
if (value == null)
{
return null;
}
var propType = prop.PropertyType;
string path = null;
switch (propType.EditorAlias)
{
case Constants.PropertyEditors.Aliases.UploadField:
path = value.ToString();
break;
case Constants.PropertyEditors.Aliases.ImageCropper:
//get the url from the json format
path = value is ImageCropperValue stronglyTyped ? stronglyTyped.Src : value.ToString();
break;
}
var url = AssembleUrl(path, current);
return url == null ? null : UrlInfo.Url(url.ToString(), culture);
}
private Uri AssembleUrl(string path, Uri current)
{
var mode = UrlMode.Auto;
if (string.IsNullOrEmpty(path))
{
return null;
}
// the stored path is absolute so we just return it as is
if (Uri.IsWellFormedUriString(path, UriKind.Absolute))
{
return new Uri(path);
}
Uri uri;
if (current == null)
{
mode = UrlMode.Relative; // best we can do
}
switch (mode)
{
case UrlMode.Absolute:
uri = new Uri(current?.GetLeftPart(UriPartial.Authority) + path);
break;
case UrlMode.Relative:
uri = new Uri(path, UriKind.Relative);
break;
case UrlMode.Auto:
var cdnUrl = ConfigurationManager.AppSettings["CmsCdnUrl"];
uri = !string.IsNullOrWhiteSpace(cdnUrl)
? new Uri(cdnUrl + path)
: new Uri(current?.GetLeftPart(UriPartial.Authority) + path);
break;
default:
throw new ArgumentOutOfRangeException(nameof(mode));
}
return UriUtility.MediaUriFromUmbraco(uri);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment