Creating Custom Formatter in ASP.NET Web API TO HANDLE SPECIFIC formatted REQUEST

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

This is a series of the article I wrote earlier in which I showed the way of handling formatted response. https://ovaismehboob.wordpress.com/2014/01/04/creating-custom-formatter-in-asp-net-web-api-for-specific-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


public class PipeFormatter : BufferedMediaTypeFormatter
{
public PipeFormatter() {
SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue(“text/pipe”)); }

public override bool CanReadType(Type type)
{
if (type == typeof(User)) {
 return true;

}
return false

}

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

 User userObject = new User();

 StreamReader reader = new StreamReader(readStream);

 string str=reader.ReadToEnd();

 String[] propArr = str.Split(new char[] { ‘|’ });

 foreach (var val in propArr) {
string[] propIntArr = val.Split(new char[] { ‘=’ });
if (propIntArr[0].ToLower().Trim().Equals(“name”)){
userObject.Name = propIntArr[1].ToString();
}
else if (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!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s