Ken Palmer
Ken Palmer

Reputation: 2445

In EPiServer 8, how can I get ContentType from a content item?

I need to detect the Content Type for an EPiServer object in EPiServer 8.0. This is to prevent the following exception that our code encounters.

EPiServer.Core.TypeMismatchException: Content with id '202' is of type 'Castle.Proxies.PDFMediaFileProxy' which does not inherit required type 'EPiServer.Core.PageData'

Here is an abbreviated snippet of code to show where we encounter the exception.

// This property in our class gets populated elswhere.
public List<IndexResponseItem> SearchResult { get; set; }

// Code in method that fails.
var repository = ServiceLocator.Current.GetInstance<IContentRepository>();
foreach (var item in SearchResult)
{
    var foo = new UrlBuilder(item.GetExternalUrl());
    IContent contentReference = UrlResolver.Current.Route(foo);
    if (contentReference != null)
    {
        // This line of code breaks.
        var currPage = repository.Get<PageData>(contentReference.ContentGuid);
    }
}

The above code works when our search returns any PageData content types. But if it hits a PDF content type, this breaks.

Getting the ContentTypeID is straightforward (via contentReference.ContentTypeID). But I want to actually examine the actual content type for each object. How can I get the ContentType? Thanks.

Upvotes: 2

Views: 4266

Answers (1)

Eric Herlitz
Eric Herlitz

Reputation: 26307

MediaFile objects isn't PageData instances so you need to verify that contentReference is PageData as well

if (contentReference != null && contentReference is PageData)
{
    var currPage = repository.Get<PageData>(contentReference.ContentGuid);
}

It does however seem as if you are building a custom implementation from Episerver Search, I'd recommend checking the examples in the documentation http://world.episerver.com/documentation/Items/Developers-Guide/Episerver-CMS/8/Search/Search-integration/

== Edit ==

To resolve content types from content items use IContentTypeRepository

// content is an IContent object
var contentTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
var contentType = contentTypeRepository.Load(content.ContentTypeID);

Upvotes: 4

Related Questions