Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to handle form post data in a Web Api controller?

In ASP.NET MVC , one can access the form post data:

var thisData = Request.Form["this.data"]; 

Is it possible to achieve the same functionality in a Web API ApiController?

like image 745
Magnus Johansson Avatar asked Jul 21 '12 15:07

Magnus Johansson


2 Answers

ASP.NET Web API has become significantly more robust in dealing with different HTTP scenarios - especially streaming. As such only media type formatters normally touch the content and have to make a coherence of the content.

In ASP.NET MVC, application/x-www-form-urlencoded content type is a first class citizen (and treated especially since this is the content type of 95% of the POST requests) and we have the FormsCollection to provide dictionary access in access, whenever it is defined as an input parameter.

In ASP.NET Web API, application/x-www-form-urlencoded is yet another content type, and supposed to be read by its MediaTypeFormatter. As such ASP.NET Web API cannot make any assumption about the Forms.

The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions's parameter as NameValueCollection:

public void Post(NameValueCollection formData) {    var value = formData["key"]; } 
like image 149
Aliostad Avatar answered Oct 12 '22 02:10

Aliostad


Well, it is not possible because HttpRequestMessage doesn't provide that kind of collection out of the box.

However, if your application is hosted under ASP.NET, you can get to the current HttpContext object and get the form values from there:

public class CarsController : ApiController {      public string[] Get() {          var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];         var foo = httpContext.Request.Form["Foo"];          return new string[] {              "Car 1",             "Car 2",             "Car 3"         };     } } 

But I am not sure if this is the best way of doing this kind of stuff.

like image 22
tugberk Avatar answered Oct 12 '22 03:10

tugberk