Web API Why do I need to use FormDataCollection?

I am just starting out with the web API and I love it in general, but I find that reading data from a POST request using "application / x-www-form-urlencoded" is a pain. I wanted to see if there is a better way to do this. My application (x-editable form) makes a simple HTTP POST request to my controller with three 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:

 public HttpResponseMessage PostSet(FormDataCollection set) {} 

I can read the form values โ€‹โ€‹from the FormDataCollection form, but can someone explain to me why I cannot just write:

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

Or match it with a model?

I thought the web API should display parameters from form values?

+4
source share
1 answer

You will need to decorate the parameter using the FromBody attribute. But this will only work for one parameter . yes, I feel like you frowned. Something like this should work:

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

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

More on this post .

+4
source

Source: https://habr.com/ru/post/1497155/


All Articles