ASP.NET web api cannot get application/x-www-form-urlencoded HTTP POST

This post is old, but I stumbled on it while searching for answer. I'll post how I got mine to work, maybe someone will find it useful.

Here's the request:

POST /api/values HTTP/1.1
Host: localhost:62798
Accept: text/json
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 51ee1c5f-acbb-335b-35d9-d2b8e62abc74

UID=200&EMAIL=john%40jones.com&FIRST_NAME=John&LAST_NAME=jones&PHONE=433-394-3324&CITY=Seattle&STATE_CODE=WA&ZIP=98105

Here's the Model:

public class SampleModel{
    public string UID { get; set; }

    public string Email { get; set; }

    public string First_Name { get; set; }

    public string Last_Name { get; set; }

    public string Phone { get; set; }

    public string City { get; set; }

    public string State_Code { get; set; }

    public string Zip { get; set; }
}

And here's the POST method that automagically(FromBody) converts urlencoded values to the model.

public HttpResponseMessage Post([FromBody] SampleModel value){

I was able to pick out any value i.e.

    SearchCity(value.City);
    SearchName(value.Last_Name);

Quoting from here:

By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.

Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.

Second, the client needs to send the value with the following format:

=value

Specifically, the name portion of the name/value pair must be empty for a simple type.

So, if you want to post data in the format data=string, you have to create complex type.

public class MyFormData
{
    public string Data { get; set; }
}

And update your controller like so:

public void Post(MyFormData formData)
{
    //your JSON string will be in formData.Data
}

Of course, other alternatives for you is to change the content type to JSON, but really depends on your requirements.


You should create an object of your data like:

public class Device
{
  public string mac {get;set;}
  public string model {get;set;}
}

then change your controller's action method like this and pass your object to this method from consume

public void Post(Device deviceData)
{
    // You can extract data like deviceData.mac, deviceData.model etc
    data.Add(deviceData);
}

You can use one of the popular library json.net for serialize/deserialize of json object in C#