Collection Form Post Parameters in WebAPI Controller

Posted by Peter Kellner on August 18, 2013 · 1 min read

There are lots of ways using ASP.NET MVC4 to collection passed in form parameters (POST) to the WebAPI Controller.  I’m not wanting to create a Model, I’m not wanting to get involved with dynamic variables, I just want the values that are posted in.  Say for example, my post looks like the following:

image

To capture both sessionId and trackId, I can have a WebAPI controller in Visual Studio that looks just like this:

namespace WebAPI.Api
{
public class SessionRpcController : ApiController
{
[HttpPost]
[ActionName("UpdateSessionTrack")]
[Authorize(Roles = "admin")]
public HttpResponseMessage
PostUpdateSessionTrack(
FormDataCollection formDataCollection)
{
var sessionId =
Convert.ToInt32
(formDataCollection.
FirstOrDefault(a => a.Key == "sessionId").
Value);
var trackId =
Convert.ToInt32
(formDataCollection.
FirstOrDefault(a => a.Key == "trackId").
Value);

// do some real work here

HttpResponseMessage response =
Request.CreateResponse(HttpStatusCode.OK);
return response;
}
}
}

Simple as that!  HTH’s