Tuesday, October 7, 2014

ASP.NET Web API error: Can't bind multiple parameters to the request's content

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:

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:

2 comments:

S W said...

I get this error with FormDataCollection:

No MediaTypeFormatter is available to read an object of type 'FormDataCollection' from content with media type 'text/plain'.

Any advice is appreciated. Thanks in advance.

S W said...

I solved it. I am using an HttpClient so I need to add this:

StringContent request = new StringContent(data);
request.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");