Collection Form Post Parameters in WebAPI Controller

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

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. Peter Kellner says:

    thanks for asking! Did Vail pass twice last week. There is no air at 10,000 feet!

  2. Neal Shea says:

    Yea, this is cool but how’s the biking going?

Follow

Get every new post delivered to your Inbox

Join other followers: