.Net Core · C#

Action Data Formats

In .NET Core standard application configuration the Content-Type header is set to:

  • text/plain – if the action method returs string
  • application/json – for all data types

JSON format is very common, but in some situation we have to return data in other format, for example in XML.
To do to that, first thing you have to do is to add AddXmlDataContractSerializerFormatters in ConfigureServices method located in Startup.cs file:

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

Next step is to use Produces attribute on the action which returned data format we want to change:

HomeController.cs

 [Produces("application/xml")]
public UserDetails GetUserDetails()
        {
            var user = new UserDetails()
            {
                FirstName = "Adam",
                LastName = "Nowak"
            };

            return user;
        }

If you run the application and call GetUserDetails action, the result will be as follows:

<?xml version="1.0"?>
<UserDetails xmlns="http://schemas.datacontract.org/2004/07/WebApplication9.Controllers" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <FirstName>Adam</FirstName>
  <LastName>Nowak</LastName>
</UserDetails>

The second option is to use FormatFilter. This type of filter specifies Content-Type based on the format value received from route data or query string:

HomeController.cs

        [FormatFilter]
        [HttpGet("Home/GetUserDetails/{format?}")]
        public UserDetails GetUserdetails()
        {
            var user = new UserDetails()
            {
                FirstName = "Adam",
                LastName = "Nowak"
            };
            return user;
        }

Above approach requires to set mapping for the format to specified media type. We can do it in ConfigureServices method (Startup.cs):

 services.AddMvc()
                .AddXmlDataContractSerializerFormatters()
                .AddMvcOptions(options =>
                {
                    options.FormatterMappings.SetMediaTypeMappingForFormat("xml", new MediaTypeHeaderValue("application/xml"));
                });

If you run application and call home/getuserdetails/json or home/getuserdetails you receive data in JSON. To get data in XML, you should call home/getuserdetails/xml.

By default, Accept header from the request is ignored and the application returns data in format specified in application configuration. However, sometimes we have to prevent it and respect the Accept header. It requires two changes in ConfigureServices method:

 services.AddMvc()
                .AddMvcOptions(options =>
                {
                    options.RespectBrowserAcceptHeader = true;
                    options.ReturnHttpNotAcceptable = true;
                });

It is also possible to retrieve data in different formats.
To define what data format should be consumed in action method, we should use Consumes attrubutes:

        [Consumes("application/xml")]
        [HttpPost]
        public IActionResult UpdateUser ([FromBody]UserDetails user)
        {

        }

        [Consumes("application/json")]
        [HttpPost]
        public IActionResult UpdateUser([FromBody]UserDetails user)
        {

        }

Leave a Reply

Your email address will not be published. Required fields are marked *