ianrathbone ianrathbone - 1 year ago 78
C# Question

Post parameter is always null

Since upgrading to RC for WebAPI I'm having some real odd issue when calling POST on my WebAPI.
I've even gone back to the basic version generated on new project. So:

public void Post(string value)

and calling from Fiddler:

User-Agent: Fiddler
Host: localhost:60725
Content-Type: application/json
Content-Length: 29

"value": "test"

When I debug, the string "value" is never being assigned to. It's just always NULL.
Anyone having this issue?

(I first saw the issue with a more complex type)

The problem is not only bound to ASP.NET MVC 4, the same problem occurs for a fresh ASP.NET MVC 3 project after RC installation

Answer Source

Since you have only one parameter, you could try decorating it with the [FromBody] attribute, or change the method to accept a DTO with value as a property, as I suggested here: MVC4 RC WebApi parameter binding

UPDATE: The official ASP.NET site was updated today with an excellent explanation: http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

In a nutshell, when sending a single simple type in the body, send the just the value prefixed with an equal sign (=), e.g. body: