How to get an IPublishedContent item from a Udi in Umbraco 10 and above

Posted written by Paul Seal on November 07, 2023 Modern .NET Umbraco

Today, my colleague asked me how he can get an IPublishedContent item from a Udi in Umbraco.

This comes up a lot and it would be great to have an answer that I can go to every time rather than searching my different projects each time for how I did it.

So this post is for my colleague and future me. Also for anyone else who finds it.

First we need to get the Udi as a string:

var uriString = content.Value<string>("author");

Get the Udi as a string.

Now we have the string value, we need to use it to create a Udi object.

//make sure we have our using statement at the top
using Umbraco.Cms.Core

//create the Udi
var udi = Udi.Create(new Uri(uriString));

Create a Udi object

Now we have it as a Udi object, we can then use that to get the IPublishedContent item from Umbraco, but it could be a media item or a content item, or even a member, who knows?

//add our using statement for the UdiEntityType usage
using static Umbraco.Cms.Core.Constants;

IPublishedContent contentItem = null;

//In this case, Umbraco is the UmbracoHelper and it is in a View.

switch(udi.EntityType)
{
    case UdiEntityType.Document:
        contentItem = Umbraco.Content(udi);
        break;
    case UdiEntityType.Media:
        contentItem = Umbraco.Media(udi);
        break;
    //you could handle other entity types below
}

Get the IPublishedContent from the cache

Here is all the code together:

string uriString = Model.Value<string>("author");
Udi udi = Udi.Create(new Uri(uriString));

IPublishedContent contentItem = null;

switch(udi.EntityType)
{
    case UdiEntityType.Document:
        contentItem = Umbraco.Content(udi);
        break;
    case UdiEntityType.Media:
        contentItem = Umbraco.Media(udi);
        break;
    //you could handle other entity types below
}

All the code together