Implementing a custom data format

If you want the Web site to serve up content in a format that is not available out of the box, you can implement and register it yourself.

Procedure

  1. In .NET, create a new subclass of the Sdl.Web.Mvc.Formats.BaseFormatter class, writing your own FormatData method to return a custom ActionResult object. The following code sample shows the basic structure of this subclass:
    using System.Web.Mvc;
    namespace MySite.Formatters
    {
        public class MyCustomFormatter : BaseFormatter
        {
            public MyCustomFormatter()
            {
    												// Specify a MIME type, for example, application/json
                AddMediaType("my-mime-type");
                // You can match multiple mime types
                AddMediaType("my-mime-type2");
                // Set ProcessModel to true if you want the data to include dynamic data added by controller actions
                this.ProcessModel = true;
                // Set AddIncludes to true if you want the data to have data from includes 
                // (for example, the page header and footer)
                this.AddIncludes = false;
            }
            public override ActionResult FormatData(ControllerContext controllerContext, object model)
            {
                return model==null ? null : new MyCustomActionResult { Data = model };
            }
        }    
        public class MyCustomActionResult : ActionResult
        {
            public Encoding ContentEncoding { get; set; }
            public object Data { get; set; }
            public override void ExecuteResult(ControllerContext context)
            {
                HttpResponseBase response = context.HttpContext.Response;
                response.ContentType = "my-mime-type";
                if (ContentEncoding != null)
                {
                    response.ContentEncoding = ContentEncoding;
                }
                if (Data != null)
                {
                    // Insert custom code here to convert the model into whatever output format you require 
                    // and write it to the response
                }
            }
        }
    }
  2. Make this new subclass available.
  3. Open the file Global.asax.cs of the Web application for editing.
  4. Add the following line:
    Sdl.Web.Mvc.Formats.DataFormatters.Add("FORMATNAME", new MySite.Formatters.MyCustomerFormatter());
    where:
    • FORMATNAME is the name of the format as you want it to be filled in as one of the values in the comma-separated list that is the value of the dataFomats property in Content Manager Explorer
    • MySite.Formatters.MyCustomerFormatter() is the constructor of the new subclass you just created.
  5. Save and close Global.asax.cs. Your custom class is now registrered.
  6. Restart the Web application.