Created
December 17, 2019 10:38
-
-
Save deMD/3937354d7c8285464a04aafa13a99d10 to your computer and use it in GitHub Desktop.
Umbraco CdnMediaUrlProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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