var contentWithKey = content as IPublishedContentWithKey;
return contentWithKey == null ? Guid.Empty : contentWithKey.Key;
Or add this method to your solution:
public static Guid GetGuid(this IPublishedContent content)
{
var contentWithKey = content as IPublishedContentWithKey;
if (contentWithKey != null)
return contentWithKey.Key;
if (content is PublishedContentWrapped)
{
contentWithKey = ((PublishedContentWrapped)content).Unwrap() as IPublishedContentWithKey;
if (contentWithKey != null)
return contentWithKey.Key;
}
return Guid.Empty;
}
Just tested this method on Umbraco 7.6.3, and it works.
public static Guid GetGuid(this IPublishedContent content)
{
var contentWithKey = content as IPublishedContentWithKey;
if (contentWithKey != null)
return contentWithKey.Key;
if (content is PublishedContentWrapped)
{
contentWithKey = ((PublishedContentWrapped)content).Unwrap() as IPublishedContentWithKey;
if (contentWithKey != null)
return contentWithKey.Key;
}
return Guid.Empty;
}
Alex's example where he uses the Unwrap method is what I've also found you have to do. Most of the time GetKey on IPublishedContent doesn't work you have to unwrap it rather than cast it to IPublishedContentWithKey to get it to behave.
Guid Issue
Hi!
I'm trying to get the GUID of a published node of my umbraco tree in my surface controller.
I have the node ID.
After calling (successfully) umbracoHelper.TypedContent(myId) i tried to get my key using GetKey() but it always return 0.
Any idea? The node is published, i can see his guid in my backend .
Umbraco version -> 7.6.3.
Thanks.
Hi Mattia
Try this code:
Or add this method to your solution:
Thanks,
Alex
Already tried, but return contentWithKey == null ? Guid.Empty : contentWithKey.Key; returns always Guid.Empty AKA contentWithKey seems to be null...
It's not right way to do it, but it works:
No no no no no please do not do this!!
:-)
This call goes straight to the database and circumvents the content cache. This is very slow and very bad for performance!
Please don't do this, ever. Unless you know what you're doing.
Anyway, have you tried this? https://github.com/Shazwazza/Articulate/blob/master/src/Articulate/Models/PublishedContentExtensions.cs#L52
It looks similar to the method above, but I can't figure out Mattia what exactly is null for you, the code on which line?
Just tested this method on Umbraco 7.6.3, and it works.
Yes, I found the same work-around.... But i would prefer not to user the content service
Alex's example where he uses the Unwrap method is what I've also found you have to do. Most of the time GetKey on IPublishedContent doesn't work you have to unwrap it rather than cast it to IPublishedContentWithKey to get it to behave.
is working on a reply...