A colleague asked me to help him out with a problem he had with a specific ASP.NET Web API controller. Let’s have a look at his controller first:
public class ProductController: ApiController | |
{ | |
public HttpResponseMessage PostProduct(int id, string productName) | |
{ | |
//Removed the content | |
} | |
} |
Inside his web application, he uses a form to post data to this specific controller. However when he runs his application, the post always fails with the following error message:
Can't bind multiple parameters to the request's content
This is by design. In ASP.NET Web API it isn’t possible to pass multiple parameters by body. As we are using a POST the form data is part of the message body. ASP.NET Web API is unable to extract the form data from the message body and set the parameter values.
To get this working, you can either replace the parameters by a FormDataCollection and do the binding yourself or you can create a POCO object to and use the built-in model binders:
public class ProductController: ApiController | |
{ | |
public HttpResponseMessage PostProduct(FormDataCollection data) | |
{ | |
var product=new Product(); | |
product.Id=Convert.ToInt32(data.Get("id")); | |
product.Name=data.Get("name"); | |
//Removed the other content | |
} | |
} |
public class ProductController: ApiController | |
{ | |
public HttpResponseMessage PostProduct(Product product) | |
{ | |
//Removed the other content | |
} | |
} |