Binding is different for MVC and Web API. By default, ASP.NET Web API binds complex types from the request message body and simple types from URI, query string, etc. Since you specified Z
, which is a class (complex type), it populates the action method parameter from body without you having to specify [FromBody]
. On the other hand, if your request is http://localhost:11485/api/profiles/aaa?z=1
without a body, it will NOT bind to your complex parameter automatically. In that case, you will need to specify [FromUri]
like this: public HttpResponseMessage aaa([FromUri]Z z)
.
On the other hand, say your action method is public HttpResponseMessage aaa(string a)
. We now have string
, which is a simple type. In this case, http://localhost:11485/api/profiles/aaa?a=1
without a message body will let Web API bind the parameter correctly without you having to specify [FromUri]
. Now, if you want to bind from body in this case, you will need to specify public HttpResponseMessage aaa([FromBody]string a)
. Of course, for this body must be =1
, for application/x-www-form-urlencoded
, without the key name of a
.
Bottom line - your parameter (simple type or complex type) determines how Web API binds. To make it work differently from the default behavior, you need to tell via FromUri
or FromBody
.
PS. Whatever I mentioned above holds good purely for the good old ASP.NET Web API (including 2). In ASP.NET 5.0 a.k.a ASP.NET vNext or ASP.NET MVC 6.0, MVC and Web API have been unified. In order for it to bind a complex type from body, you must specify [FromBody]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…