See my discussion https://stackoverflow.com/a/75263628/5555938 on [FromBody]
. It explains everything in great detail!
But in summary...
Angular
, like all JavaScript API's, does NOT post traditional HTML form field data (name-value pairs in the HttpRequest body). These JavaScript API's use XMLHttpRequest-type
POSTS that supersede the traditional HTML browser-based form POST and send data directly in a special JSON Content-type message directly to the server.
What Angular people do not tell you is that this is not HTML-type <form>
data POST's. Angular hijacks all form field post calls in the web browser and sends its own data to the server.
So many modern Web API endpoints are not set up to receive these Angular HttpRequests as special POST JSON formats
without additional "hints" as to what type of modeled data they are receiving. Remember JSON is just a plain text string, only identified as "special text" via the JSON mime-type or Content-type Http Header information attached with the data saying its JSON object notation! JSON objects are just data packaged into these special formatted text strings. But most servers do not know this. Some do.
But that is why in ASP.NET Core and WebAPI Core we now have two decorators to help us: [FromBody]
and [FromForm]
That is what [FromBody]
does in ASP.NET Core or WebAPI. It tells the end point to listen for JSON data or text strings coming in as objects and helps convert them into your modeled data types in the parameter list of the ASP.NET endpoint method.
[FromForm]
is the opposite....it is designed for ASP.NET MVC and more traditional HTML name-value data posts to the server that don't require all that extra JavaScript and JSON formatting. Use that if you are posting plain HTML <form>
posts of data to the server from a plain HTML web page.
So, again...[FromBody]
does NOT accept HTML Form field name-value pairs like [FromForm]
. It is designed for API's like Angular that send JSON data.
Since you are using Angular, you should set up your server endpoints with [FromBody]
.
Keep in mind, however, on your client Angular-side, sending data to the server now requires the following:
- JavaScript POST Request manually sent to the Web API server
- JavaScript Http Header with JSON mime-type attached
- JavaScript Http Body with form field extracted data, reformatted and submitted as JSON. Traditional HTML POST name-value pairs will not work!
However, because Angular Observables
and HttpClientModule
calls take care of all that for you, you should be good to go! If you are NOT using Angular, however, my list above would apply to your custom JavaScript calls sending JSON to your new endpoint.