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?
The [ApiController] attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters.
NET Core Web Api. When applied to the member of a type, specifies that the member is not part of a data contract and is not serialized. You can fill the id later on in the controller and still maintain one viewmodel.
It is very important and basic for Web APIs. The namespace for this class is “System. Web. Http”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With