Umbraco 中获取一个media item的文件路径 file path
我们要使用UmbracoHelper, 这里就需要用到我们在之前的blog里面写的UmbracoContext
参看这个blog https://www.cnblogs.com/wphl-27/p/9927044.html
public class ContextHelpers { public static UmbracoContext EnsureUmbracoContext() {
if(UmbracoContext != null) { return UmbracoContext.Current; } var dummyHttpContext = new HttpContextWrapper(new HttpContext(new SimpleWorkerRequest("blah.aspx", "", new StringWriter()))); return UmbracoContext.EnsureContext( dummyHttpContext, ApplicationContext.Current, new WebSecurity(dummyHttpContext, ApplicationContext.Current), UmbracoConfig.For.UmbracoSettings(), UrlProviderResolver.Current.Providers, false); } }
1. 在View 中
在View中写如下代码
UmbracoHelper uHelper = new UmbracoHelper(ContextHelper.EnsureUmbracoContext()); string mediaUrl = ""; if (CurrentPage.HasValue(propertyName)) { var mediaItem = uHelper.Media(CurrentPage.propertyName.ToString()); mediaUrl = mediaItem.umbracoFile; } return mediaUrl;
2. 在后台代码中写
using Umbraco.Web; public static string GetMediaUrlFromPropertyName(dynamic contentItem, string propertyName) { UmbracoHelper uHelper = new UmbracoHelper(ContextHelper.EnsureUmbracoContext()); string mediaUrl = ""; if (contentItem.HasValue(propertyName)) { var mediaItem = uHelper.Media(contentItem.GetPropertyValue(propertyName)); mediaUrl = mediaItem.umbracoFile; } return mediaUrl; }
原文请参看 https://codeshare.co.uk/blog/how-to-get-the-file-path-of-a-media-item-in-umbraco/