Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating Custom Formatter in ASP.Net Web API to handle specific formatted request

DZone's Guide to

Creating Custom Formatter in ASP.Net Web API to handle specific formatted request

·
Free Resource

In this article I will show you how to create a custom formatter in ASP.Net Web API to send objects in Request body with a specific format.

This is a sequel to the article I wrote earlier in which I showed the way to handle a formatted response. 

Formatters in ASP .NET Web API plays an important role, when the request comes to the server, depending on the media-type, determines which formatter has to be used to parse the request and assemble the data into appropriate format as response. In ASP.Net Web API when the request is made by the user, Web API framework checks if it is Simple Type or a Complex Type. All types like string, integers, etc. are simple types and by default ASP.Net Web API read those values from URI and uses Model binding. On the other hand for complex types, ASP.Net WEB API framework read it from request body by default (the behavior can be overridden) an depending on the content-type load specific formatter from the list of formatters available in HttpConfiguration list.

Let suppose we want to send object in pipe format. In this post I will send a user object in request body in below format.

User object have two properties namely Name and Position and we need to send data in below format

Request Body:  Name=Ovais | Position=Technical Architect

This can be done by implementing a custom formatter. When you are creating a custom formatter in ASP.Net Web API, you have two options one is when the request is arrived on server and you want to return the data in specific format or when the request arrives and you want to read/parse the data in specific format.

Steps to follow.

1.  Create a new Web API project in Visual Studio

2.  Add a new User class having two string properties namely Name and Position

3.  Add a new folder named “Infrastructure”. It’s always a good practice to place all the core level classes in particular folder. In my case I have named it Infrastructure.

4.  Add a new class and named it PipeFormatter

5.  Derive this class from BufferedMediaTypeFormatter

6.  Override CanReadType and ReadToStream methods and add the logic to handle incoming request

7.  Below is the complete code of PipeFormatter class

  publicclassPipeFormatter : BufferedMediaTypeFormatter

  {

  public PipeFormatter()

  {

  SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/pipe"));

  }

  publicoverridebool CanReadType(Type type)

  {

  if (type == typeof(User))

  {

  returntrue;

  }

  returnfalse;

 

  }

  publicoverrideobject ReadFromStream(Type type, System.IO.Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger, System.Threading.CancellationToken cancellationToken)

  {

  User userObject = newUser();

  StreamReader reader = newStreamReader(readStream);

  string str=reader.ReadToEnd();

  String[] propArr = str.Split(newchar[] { '|' });

  foreach (var val in propArr)

  {

  string[] propIntArr = val.Split(newchar[] { '=' });

  if (propIntArr[0].ToLower().Trim().Equals("name"))

  {

  userObject.Name = propIntArr[1].ToString();

  }

  elseif (propIntArr[0].ToLower().Trim().Equals("position"))

  {

  userObject.Position = propIntArr[1].ToString();

  }

  }

  return userObject;

  }

  }

8.  In the above code you can see that I have added the “text/pipe” media type in the supported media type list. This you have to add it so you can specify the Content-Type attribute when sending HTTP request.

9.  Now open the WebApiConfig class placed under App_Start folder

10.  Add an entry in the config.Formatters collection as below.

  config.Formatters.Add(new WebApplication1.Infrastructure.PipeFormatter());

11.  Build the project and run.

12.  In order to test I used Fiddler

13.  Requesting from fiddler


14. ReadFromStream method is called and populate the User object 


15. And finally on my controller Post method I am receiving this object.


Hope this helps!

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}