A comment on my last post, "Custom output for EPiServer pages", said that it would me more clean to have content rendered based on content negotiation, rather than on a querystring parameter.
I don’t look on an url segment as a querystring, and you cannot always force the Content-Type or Accept header for the one browsing your site. So, I think requesting a different output through the url has it’s merits and is also a clean solution.
That being said, it does not take much to use the custom output library I created in the way Arve suggested. Display Channels to the rescue.
public class JsonChannel : DisplayChannel { public override string ChannelName { get { return OutputConstants.JSON; } } public override bool IsActive(HttpContextBase context) { if (context == null) { return false; } return ChannelSettings.Instance.EnableJSON && context.Request.AcceptTypes != null && context.Request.AcceptTypes.Any(t => t.Equals(OutputConstants.ApplicationJSON, StringComparison.OrdinalIgnoreCase)); } }
In your template you can then render the output as requested based on the Active Channel.
List<DisplayChannel> channels = ServiceLocator.Current.GetInstance<DisplayChannelService>() .GetActiveChannels(new HttpContextWrapper(HttpContext.Current)) .ToList(); bool isJsonChannel = channels.Any( c => string.Equals(c.ChannelName, OutputConstants.JSON, StringComparison.OrdinalIgnoreCase)); if (isJsonChannel) { JsonOutputFormat jsonOutputFormat = new JsonOutputFormat(); jsonOutputFormat.HandleFormat(currentPage, new HttpContextWrapper(HttpContext.Current)); }
That’s it basically. I created a base template page that handles the different outputs, or you can use the method from the outputhelper.
OutputHelper.UseActiveChannel(this.CurrentPage);
The complete add-on to the output formats can be found on GitHub
One thought on “Custom output for EPiServer pages, pt 2”