Sebastian Nemeth
Sebastian Nemeth

Reputation: 6175

Web API - Why do I have to use a FormDataCollection?

I'm just getting start with Web API, and loving it generally, but finding that reading data from a POST request with 'application/x-www-form-urlencoded' is a pain. I wanted to see if there's a better way to do this. My application (an x-editable form) makes a simple HTTP POST request to my controller, with 3 values: pk, name, value.

The request is as follows:

POST http://localhost/XXXX.Website/api/Category/Set HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 39
Accept: */*
Origin: http://localhost
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost/XXXX.Website/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: ...

name=myPropertyName&value=myTestValue&pk=1

My Action method in my ApiController is:

public HttpResponseMessage PostSet(FormDataCollection set) {}

I can read the form values from the FormDataCollection fine, but can someone please explain to me why I can't simply write:

public HttpResponseMessage PostSet(string name, string value, id pk) {}

Or map it to a model?

I thought Web API was supposed to be able to map parameters from form values?

Upvotes: 5

Views: 6981

Answers (1)

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

You will need to decorate the parameter using FromBody attribute. But that would work only for one parameter. yeah, I can sense you frowning. Something like this should work:

public HttpResponseMessage PostSet([FromBody] string name) {}

But, good news is that you can bind your form parameters to a Model using the [ModelBinder] attribute.

Check out this post for details.

Upvotes: 7

Related Questions