Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 430
Sebastian Nemeth Avatar asked Aug 15 '13 02:08

Sebastian Nemeth


People also ask

What is the purpose of the ApiController attribute?

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.

What is the use of Ignoredatamember in Web API?

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.

What namespace is required for Web API?

It is very important and basic for Web APIs. The namespace for this class is “System. Web. Http”.


1 Answers

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.

like image 182
Srikanth Venugopalan Avatar answered Sep 20 '22 02:09

Srikanth Venugopalan