Get the URL for a Media Item by Udi in Umbraco 8

Enjoy This Quick and Useful Code Snippet

Get the URL for a Media Item by Udi in Umbraco 8

I have been neck-deep in Umbraco 8 for the last couple of months working on a client project. Really loving it so far. Lot's of things in the APIs have changed and currently, there is not a lot of documentation for many of those changes. Today, I came across a situation where I had the Udi of a media item but what I really needed was the url to the file. If you are not familiar with what an Udi is, you can view the docs here. It's what is returned when you query IContent for a reference to media or other content types. To get the url for a media item by Udi, here is what you do:

// Get the Udi: umb://media/d65ecc138225414892293c3e0c7fc183
var hero = content.GetValue("heroImage");
if (!string.IsNullOrEmpty(hero))
     // Get the guid from this string.
     var imageGuidUdi = Udi.Parse(hero);
     // Get the ID of the node!
     var imageNodeId = Current.Services.EntityService.GetId(imageGuidUdi);
     if (imageNodeId.Success)
          IMedia mediaItem = Current.Services.MediaService.GetById(imageNodeId.Result);

          fullHeroImageUrl =$"{_BaseUrl}{mediaItem.GetUrl("umbracoFile",Current.Logger)}";

And there you have it. In my case, I needed to send the fully-qualified url of the item, so that is why I have the variable _BaseUrl. Otherwise, pretty straight-forward. Hopefully, you will find it useful. I have run into a bunch of undocumented changes so far in Umbraco 8. I will be posting more code as time allows. Umbraco 8 so far for me has been pretty awesome and I am excited to keep digging and share more code in the future.

0 comment(s) in response to Get the URL for a Media Item by Udi in Umbraco 8

Have a comment?