.NET Core 2 POST接口FromBody参数绑定失败问题求助
Hey there! Let's break down why your [FromBody] parameters aren't binding correctly and how to fix it.
The Root Cause
In .NET Core, the [FromBody] attribute is designed to bind one single complex type from the request body (since the body is a single JSON payload). When you try to use multiple [FromBody] parameters (like separate string name and string email), the framework can't map the JSON object to multiple individual simple types—it expects a single object that matches the structure of your request payload.
Solution 1: Use a DTO (Data Transfer Object) Class (Recommended)
This is the cleanest, most maintainable approach. Create a class that mirrors the structure of the JSON data you're sending from Angular:
// Define a DTO to match your request payload public class BeepRequestDto { public string Name { get; set; } public string Email { get; set; } }
Then update your API endpoint to accept this DTO with [FromBody]:
[HttpPost("api/Beep")] public IActionResult Beep([FromBody] BeepRequestDto request) { // Access request.Name and request.Email here if (request == null) { return BadRequest("Invalid request data"); } // Your business logic goes here return Ok($"Received: {request.Name}, {request.Email}"); }
Solution 2: Fix Your Angular Request Syntax
Looking at your Angular code, there's a small syntax error that might be causing issues with the request headers. Make sure the headers option is passed as the third parameter to post() (you had an extra closing bracket before it):
this._client.post( "http://localhost:4300/api/Beep", { name: name, email: email }, { headers: new HttpHeaders({ "Content-Type": "application/json" }) } ).subscribe(response => { // Handle response }, error => { // Handle error });
This ensures the Content-Type header is correctly set, which is required for .NET Core to parse the JSON body.
Solution 3: Bind to a JObject (Alternative, Not Recommended)
If you really don't want to create a DTO, you can bind the entire JSON body to a JObject (from Newtonsoft.Json) and extract the values manually:
using Newtonsoft.Json.Linq; [HttpPost("api/Beep")] public IActionResult Beep([FromBody] JObject requestData) { string name = requestData["name"]?.ToString(); string email = requestData["email"]?.ToString(); if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email)) { return BadRequest("Missing required fields"); } // Your logic here return Ok(); }
Note: This approach is less type-safe and harder to maintain compared to using a DTO, so it's better to stick with the first solution.
Quick Checks
- Ensure your .NET Core 2 project has the necessary JSON configuration (it should be included by default in Startup.cs with
services.AddMvc()). - Verify that the JSON keys from Angular (
name,email) match the property names in your DTO (case-insensitive by default, but it's best to keep them consistent).
内容的提问来源于stack exchange,提问作者DonkeyBanana

