Is there a way to handle form post data in a Web Api controller?

ASP.NET Web API has become significantly more robust in dealing with different HTTP scenarios – especially streaming. As such only media type formatters normally touch the content and have to make a coherence of the content.

In ASP.NET MVC, application/x-www-form-urlencoded content type is a first class citizen (and treated especially since this is the content type of 95% of the POST requests) and we have the FormsCollection to provide dictionary access in access, whenever it is defined as an input parameter.

In ASP.NET Web API, application/x-www-form-urlencoded is yet another content type, and supposed to be read by its MediaTypeFormatter. As such ASP.NET Web API cannot make any assumption about the Forms.

The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions’s parameter as NameValueCollection:

public void Post(NameValueCollection formData)
{
   var value = formData["key"];
}

Leave a Comment