joydip_kanjilal
Contributor

How to format response data in ASP.NET Core

how-to
Jan 13, 20205 mins
C#Microsoft .NETSoftware Development

Take advantage of FormatFilterAttribute in ASP.NET Core to format response data based on the request URL.

abstract binary vortex matrix motion digtial transformation disruption  by simon carter peter crowt
Credit: Simon Carter / Getty

ASP.NET Core provides excellent support for formatting data, whether it’s output data or data in the request body. When working in ASP.NET Core, your API methods will typically return JSON data, but you can also return data in formats other than JSON such as XML.

For example, a call to /api/default.json should return data from the API method in JSON format, whereas a call to /api/default.xml should return the data in XML format. In this article, we’ll look at how we can control the format in which data will be returned from ASP.NET Core based on the extension of the URL.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.  

Create an ASP.NET Core API project

First off, let’s create an ASP.NET Core API project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.Net Core API project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.
  7. In the “Create New ASP.NET Core Web Application” window, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top. I’ll be using ASP.NET Core 3.0 here.
  8. Select “API” as the project template to create a new ASP.NET Core API application. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. Click Create. 

You should have a new ASP.NET Core API project ready to go in Visual Studio. Next select the Controllers solution folder in the Solution Explorer Window and click “Add -> Controller…” to create a new controller named DefaultController. We’ll use this project and controller in the subsequent sections of this article.

Install the XML formatter NuGet package for ASP.NET Core

Now that we have created an ASP.NET Core application in Visual Studio, the next thing you should do is install the necessary NuGet package(s). Since ASP.NET Core is modular, you will need to add any functionality explicitly. To add support for the XML formatter, you should add the Microsoft.AspNetCore.Mvc.Formatters.Xml NuGet package.

You can install this package from the NuGet Package Manager window in Visual Studio 2019. Alternatively, you can write the following command to install this package via the .NET CLI.

dotnet add package Microsoft.AspNetCore.Mvc.Formatters.Xml

Use the FormatFilter attribute in ASP.NET Core

You can take advantage of the FormatFilter attribute to specify the output format via the URL. The following code snippet shows how you can include the {format} parameter to achieve this.

 [HttpGet("{id}.{format?}")]
 public string Get(int id)
 {
    return "The value is: "+id.ToString();
 }

Now that the FormatFilter attribute has been applied to the action method, you can test your API method using the JSON formatter as shown below:

http://localhost:5239/api/default/10

or

http://localhost:5239/api/default/10.json

Since JSON formatter is registered with the pipeline by default and the XML formatter has not been added and configured yet, an attempt to test your API method using the following URL will result in an HTTP 404 error.

http://localhost:5239/api/default/10.xml

Here is the complete source code of the DefaultController class for your reference:

[Route("api/[controller]")]
[ApiController]
 [FormatFilter]
 public class DefaultController : ControllerBase
 {
     [HttpGet("{id}.{format?}")]
     public string Get(int id)
     {
         return "The value is: "+id.ToString();
     }
 }

Add the XML serialization formatters method in ASP.NET Core 

You can leverage the AddXmlSerializerFormatters() method to add support for XML serialization formatters for both input and output data as shown in the code snippet given below.

public void ConfigureServices(IServiceCollection services)
{
   services.AddControllers().AddXmlSerializerFormatters();
}

You can also call the AddXmlSerializerFormatters() method as shown below.

public void ConfigureServices(IServiceCollection services)
 {
    services.AddMvc().AddXmlSerializerFormatters();
 }

If you would like to format the output as XML but not read XML from the request body, you can write the following code in the ConfigureServices method of the Startup class.

services.AddMvc(options =>
    {
        options.OutputFormatters.Add(new
        XmlSerializerOutputFormatter());
    });

Finally, run the application and browse to the following URL:

http://localhost:5239/api/default/10.xml

The output should appear as shown in the screen image below.

xml formatter in aspnet core IDG

Figure 1: XML formatter in action!

The FormatFilterAttribute can read the format to be used from the URL in ASP.NET Core. Once you have applied this attribute to your action methods, you can test your action methods using the formatters available by specifying the formatter to be used in the suffix of the URL.

The AddXmlSerializerFormatters() extension method enables you to add both the input and output XML formatters to the request processing pipeline in ASP.NET Core. Note that besides XML and JSON formatters, you can use custom formatters as well.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author