Custom Formatter in.NET Core Web API with Content Negotiation

Content negotiation is the process of selecting the optimal resource for a response when many resource representations are available. For a variety of reasons, content negotiation may not be utilized as frequently as it may be despite being an HTTP function for some time. In short, content negotiation lets you choose—or better yet, “negotiate”—the content that gets returned when you send out a REST API request.

Custom Formatters

Assume that content negotiation for non-boxed types needs to be enabled for our public REST API that we are implementing. ASP.NET Core can be used to generate custom formats. Their intention is to give you the ability to create your own format for any type of media that you need to manage.

The following technique can be used to create the custom formatter.

  • Make a class for output formatting that is derived from TextOutputFormatter.
  • Make a TextInputformatter class-derived input formatted class.
  • As with the XML format, add input and output classes to the InputFormatters and OutputFormatters collections.

As an illustration, let’s put in place a custom CSV output format.

Implementing a Custom Formatter

We only need to implement an output formatter because, for the purposes of this article, formatting responses is all that is relevant. Only in the event that a request body contained a corresponding type would we require an input format.

The goal is to format a response that will yield a CSV file containing a list of blogs and the lists of blog posts that correspond with them.

To our project, let’s add a CsvOutputFormatter class.

public class CsvOutputFormatter : TextOutputFormatter
{
    public CsvOutputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/csv"));
        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }

    protected override bool CanWriteType(Type? type)
    {
        return typeof(Emp).IsAssignableFrom(type)
             || typeof(IEnumerable<Emp>).IsAssignableFrom(type);
    }

    public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
    {
        var response = context.HttpContext.Response;
        var buffer = new StringBuilder();

        if (context.Object is IEnumerable<Emp>)
        {
            foreach (var emp in (IEnumerable<Emp>)context.Object)
            {
                FormatCsv(buffer, emp);
            }
        }

        await response.WriteAsync(buffer.ToString(), selectedEncoding);
    }

    private static void FormatCsv(StringBuilder buffer, Emp emp)
    {
        buffer.AppendLine($"{emp.Id},\"{emp.Name},\"{emp.Mno},\"{emp.Salary},\"{emp.Type}\"");
    }
}

Here are some points to consider.

We specify the media type and encodings that this formatter should parse in the constructor.

The overridden CanWriteType method indicates whether or not this serializer can write the Blog type. The response is created using the WriteResponseBodyAsync method. Lastly, the FormatCsv method allows us to format a response exactly how we want it.

Implementing the class is fairly simple, and the FormatCsv method logic should be your primary focus.

All that’s left to do is include the recently created CsvOutputFormatter in the AddMvcOptions() method’s list of OutputFormatters.

builder.Services.AddControllers(options =>
{
    options.RespectBrowserAcceptHeader = true;
    options.ReturnHttpNotAcceptable = true;

}).AddXmlSerializerFormatters()
.AddMvcOptions(options => options.OutputFormatters.Add(new CsvOutputFormatter()));

Let’s try this now and see if it functions as intended. This time, in a Postman request, the application/CSV will be used as the value for the Accept header.


After configuring the custom formatter, let’s try using the JSON API responses and check if that is working or not.

Let’s try using the XML API responses and see if that is working or not.

We learned the new technique and evolved together.

Happy coding!

Best and Most Recommended ASP.NET Core 8.0.4 Hosting

Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 8.0.4 web ranking. HostForLIFEASP.NET is highly recommended. In Europe, HostForLIFEASP.NET is the most popular option for first-time web hosts searching for an affordable plan.

Their standard price begins at only € 3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFEASP.NET guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.

By providing reseller hosting accounts, HostForLIFEASP.NET also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.