Custom output for EPiServer pages, pt 3

Using the Output channels within MVC requires a slightly different approach than with WebForms.

So, I created a few Controllers

  • A JsonController that handles the output for JSON.
  • A XmlController that handles the output for XML.
  • A TxtController that handles the output for TXT.
  • A PdfController that handles the output for PDF.

The Channels get initialized within an InitializationModule.

This module depends on the modules from my last two posts, "Custom output for EPiServer pages" and "Custom output for EPiServer pages, pt 2". I have refactored some of the code in those to make it reusable.

The code

As I said, the channels get initialized in the InitializationModule.

context.Locate.DisplayChannelService()
                .RegisterDisplayMode(
                    new DefaultDisplayMode(OutputConstants.JSON) { ContextCondition = ChannelHelper.IsJsonDisplayModeActive }, 
                    0);

The check if the Channel is active is one of the refactored methods.

public static bool IsJsonDisplayModeActive(HttpContextBase httpContext)
        {
            return
                ServiceLocator.Current.GetInstance<DisplayChannelService>().GetActiveChannels(httpContext)
                    .Any(c => string.Equals(c.ChannelName, OutputConstants.JSON, StringComparison.OrdinalIgnoreCase));
        }

For each format I created a controller, with a TemplateDescriptor attribute, this way every page can be rendered for the desired output.

[TemplateDescriptor(Inherited = true, Tags = new[] { OutputConstants.JSON })]
    public class JsonController : PageController<PageData>
    {
        public ActionResult Index(PageData currentPage)
        {
            OutputHelper.HandleJson(currentPage);

            return new EmptyResult();
        }

That’s it really. Nothing more to it.

The code is on GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s