Background
I am coding an API layer in C# using MVC 4 Web API Project (ASP.NET).
I have written a test action in my controller like this:
[System.Web.Mvc.HttpPost]
public string TestAction(FormCollection fc)
{
return "test";
}
I am using Poster in FireFox to test a form post:
- content-type is set to application/x-www-form-urlencoded
- Body from parameters is set to foo=bar&bar=foo
Here is my route:
RouteTable.Routes.MapHttpRoute("PostDefault", "{controller}/{action}");
Question
I am able to hit the controller with no problem when posting a url and parameters from Poster, but if I put a breakpoint on return "test"; and then hover over the FormCollection that is passed in (fc) It shows that an empty array of strings was passed in rather than my values (e.g. string[0]).
I have done this loads of times using jQuery $.post() on the client with no problems receiving the form collection.
What is it failing in this case?
Thanks,
Matt
It seems that this is an action defined inside an API controller (
ApiController). If this is the case you cannot useFormCollection. This is used for normal controller actions, not API controllers (personally I don’t use it even in normal controller actions but that’s another topic, see the next paragraph to understand what I am using instead).You should define a view model:
and then have your controller action take this view model as parameter:
Notice that the correct attribute for an API controller is
[System.Web.Http.HttpPost]and not[System.Web.Mvc.HttpPost]as in your code.Also I would recommend you sticking to RESTful conventions:
and then:
Now the HTTP Verb (POST in this case) determines the controller action to be invoked: