Custom Formatters In ASP.NET Core MVC / Web API

Introduction
 
ASP.NET Core (MVC / Web API) applications communicate to other applications by using built-in formats, such as JSON, XML, or plain text. By default, ASP.NET Core MVC supports built-in format for data exchange using JSON, XML, or plain text. We can also add the support for custom format by creating custom formatters.
 
In this article, we will learn how to create custom formatters in ASP.NET Core MVC. We can use custom formatters if we want the content negotiation process to support a content type which is not supported by built-in formatters.
 
Following are the step to create a custom formatter,
  1. Create output formatter (if we require serializing the data to send to the client)
  2. Create input formatter (if we require deserializing the data received from the client)
  3. Add the instance(s) of our formatter to the InputFormatters and OutputFormatters collections in MVCOptions.
Create Custom formatter class
 
To create custom formatter class, we need to derive class from appropriate base class. There are many built-in formatter classes available for input formatters, such as TextInputFormatter, JsonInputFormatter, and XmlDataContractSerializerInputFormatter etc. The InputFormatter is the base class of all input formatters and also, all the input formatters implement IInputFormatter interface.
 
Similarly, for the output formatter, there are many built-in formatter classes available for output formatter, such as TextOutputFormatter, JsonOutputFormatter, and XmlDataContractSerializerOutputFormatter etc. The OutputFormatter is the base class of all output formatters and also, all the output formatters implement IOutputFormatter interface.
 
To demonstrate the example, I have inherited the class from the TextInputFormatter or TextOutputFormatter base class.
  1. namespace CustomFormatter.Formatters  
  2. {  
  3.     using Microsoft.AspNetCore.Mvc.Formatters;  
  4.     using System;  
  5.     using System.Text;  
  6.     using System.Threading.Tasks;  
  7.     public class CustomOutputFormatter : TextOutputFormatter  
  8.     {  
  9.         public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)  
  10.         {  
  11.             throw new NotImplementedException();  
  12.         }  
  13.     }  
  14. }  
The next step is to specify valid media type and encoding within constructor of the formatter class. We can specify the media types and encodings by adding the SupportedMediaTypes and SupportedEncodings collections.
  1. public CustomOutputFormatter()  
  2. {  
  3.     SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/CustomFormat"));  
  4.   
  5.     SupportedEncodings.Add(Encoding.UTF8);  
  6.     SupportedEncodings.Add(Encoding.Unicode);  
  7. }  
Next step is to override CanReadType and CanWriteType method of the base class. In these methods, we can deserialize into specify the type (CanReadType) or serialize from the type (CanWriteType).
 
To demonstrate the example, I have created user defined types called "Employee". So, we might only be able to create custom formatter text from this type (Employee) and vice versa.
 
In some cases, we might need to use CanWriteResult instead of CanWriteType method. Followings are some scenarios in which we need to use CanWriteResult method, 
  • Our Action method returns the Model class
  • The derived type classes might be returned at runtime
  • If we need to know which derived class was returned by the action at runtime?
For example, our action method returns a "User" type but it might return either "Employee" or "Customer" type that derives from "User" type. If we want our formatter to only handle "Employee" objects, check the type of Object in contextObject provided by CanWriteResult method. It is not necessary to use CanWriteResult method when our action method returns IActionResult. In this case, CanWriteType method can receive the runtime type.
  1. protected override bool CanWriteType(Type type)  
  2. {  
  3.     if (typeof(Employee).IsAssignableFrom(type)  
  4.         || typeof(IEnumerable<Employee>).IsAssignableFrom(type))  
  5.     {  
  6.         return base.CanWriteType(type);  
  7.     }  
  8.     return false;  
  9. }  
Next step is to override WriteResponseBodyAsync method. This method returns response in required format. To demonstrate the example, I have sent employee data in pipe format.
  1. public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)  
  2. {  
  3.     IServiceProvider serviceProvider = context.HttpContext.RequestServices;  
  4.     var response = context.HttpContext.Response;  
  5.   
  6.     var buffer = new StringBuilder();  
  7.     if (context.Object is IEnumerable<Employee>)  
  8.     {  
  9.         foreach (var employee in context.Object as IEnumerable<Employee>)  
  10.         {  
  11.             FormatData(buffer, employee);  
  12.         }  
  13.     }  
  14.     else  
  15.     {  
  16.         var employee = context.Object as Employee;  
  17.         FormatData(buffer, employee);  
  18.     }  
  19.     return response.WriteAsync(buffer.ToString());  
  20. }  
  21.   
  22. private static void FormatData(StringBuilder buffer, Employee employee)  
  23. {  
  24.     buffer.Append("BEGIN|");  
  25.     buffer.AppendFormat("VERSION:1.0|");  
  26.     buffer.AppendFormat($"Data:{employee.Id}|{employee.EmployeeCode}|{employee.FirstName}|{employee.LastName}");  
  27.     buffer.Append("|END");  
  28. }  
The final step is to configure MVC to use a custom formatter. To use custom formatter, add the instance of the formatter class to OutputFormatters or InputFormatters collection MvsOption.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     // Add framework services.  
  4.     services.AddMvc(  
  5.             option =>  
  6.             {  
  7.                 option.OutputFormatters.Insert(0, new CustomOutputFormatter());  
  8.                 option.InputFormatters.Add(new CustomInputFormatter());  
  9.                 option.FormatterMappings.SetMediaTypeMappingForFormat("cu-for", MediaTypeHeaderValue.Parse("text/cu-for"));  
  10.             }  
  11.         );  
  12. }  
Here, I have added our custom formatter at 0 (zero) position of the OutputFormatters or InputFormatters collection, so our custom formatter has the highest priority.
 
Output

Custom Formatters In ASP.NET Core 
 
Similarly, we can also create input formatter that accepts the data in particular format and converts it in to required format. Following example code is input formatter that formats incoming data to Employee model.
  1. namespace CustomFormatter.Formatters  
  2. {  
  3.     using Microsoft.AspNetCore.Mvc.Formatters;  
  4.     using Microsoft.Net.Http.Headers;  
  5.     using System;  
  6.     using System.IO;  
  7.     using System.Text;  
  8.     using System.Threading.Tasks;  
  9.     public class CustomInputFormatter : TextInputFormatter  
  10.     {  
  11.         public CustomInputFormatter()  
  12.         {  
  13.             SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/cu-for"));  
  14.   
  15.             SupportedEncodings.Add(Encoding.UTF8);  
  16.             SupportedEncodings.Add(Encoding.Unicode);  
  17.         }  
  18.   
  19.   
  20.         protected override bool CanReadType(Type type)  
  21.         {  
  22.             if (type == typeof(Employee))  
  23.             {  
  24.                 return base.CanReadType(type);  
  25.             }  
  26.             return false;  
  27.         }  
  28.         public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)  
  29.         {  
  30.             if (context == null)  
  31.             {  
  32.                 throw new ArgumentNullException(nameof(context));  
  33.             }  
  34.   
  35.             if (encoding == null)  
  36.             {  
  37.                 throw new ArgumentNullException(nameof(encoding));  
  38.             }  
  39.   
  40.             var request = context.HttpContext.Request;  
  41.   
  42.             using (var reader = new StreamReader(request.Body, encoding))  
  43.             {  
  44.                 try  
  45.                 {  
  46.                     var line = await reader.ReadLineAsync();  
  47.                     if (!line.StartsWith("BEGIN|VERSION:1.0|"))  
  48.                     {  
  49.                         var errorMessage = $"Data must start with 'BEGIN|VERSION:1.0|'";  
  50.                         context.ModelState.TryAddModelError(context.ModelName, errorMessage);  
  51.                         throw new Exception(errorMessage);  
  52.                     }  
  53.                     if (!line.EndsWith("|END"))  
  54.                     {  
  55.                         var errorMessage = $"Data must end with '|END'";  
  56.                         context.ModelState.TryAddModelError(context.ModelName, errorMessage);  
  57.                         throw new Exception(errorMessage);  
  58.                     }  
  59.   
  60.                     var split = line.Substring(line.IndexOf("Data:") + 5).Split(new char[] { '|' });  
  61.                     var emp = new Employee()  
  62.                     {  
  63.                         Id = Convert.ToInt32(split[0]),  
  64.                         EmployeeCode = split[1],  
  65.                         FirstName = split[2],  
  66.                         LastName = split[3]  
  67.                     };  
  68.   
  69.                     return await InputFormatterResult.SuccessAsync(emp);  
  70.                 }  
  71.                 catch  
  72.                 {  
  73.                     return await InputFormatterResult.FailureAsync();  
  74.                 }  
  75.             }  
  76.         }  
  77.     }  
  78. }  
Output

Custom Formatters In ASP.NET Core
 
Summary
 
ASP.NET Core provides facility to create our own formatter. There are many built-in formatters supported by ASP.NET Core, such as JSON, XML, and plain text. Custom formatter is very useful when we interact with any third party system which accepts data in a specific format and sends the data in that specific format. Using custom formatter, we can add support to additional formats.
 
You can view or download the source code from the following link.