.NET Core 2.0 POST请求数据无法绑定至对象的问题咨询
Hey there, let’s work through this model binding issue together—it’s a super common snag in .NET Core 2.0, so I’ve got actionable steps to get your Album.AlbumName populated correctly.
1. Add the [FromBody] Attribute to Your Controller Parameter
In .NET Core 2.0, complex types don’t automatically bind from the request body unless you explicitly tell the framework to do so. Make sure your Post method includes the [FromBody] attribute on the Album parameter:
[HttpPost] public IActionResult Post([FromBody] Album album) { if (ModelState.IsValid) { // Your logic here return Ok(album); } return BadRequest(ModelState); }
Without this attribute, the framework might try to bind from query strings or form data instead of the JSON body, leading to null values.
2. Ensure Your Album Class Meets Binding Requirements
Model binding only works with public properties that have both getters and setters. Double-check your class definition:
public class Album { // Must be public with get/set accessors public string AlbumName { get; set; } // Add other properties as needed, following the same pattern }
If your property names don’t match the JSON keys in the request (e.g., request uses albumName but your class has AlbumName), use the [JsonProperty] attribute to map them (requires the Newtonsoft.Json package, which is default in .NET Core 2.0):
using Newtonsoft.Json; public class Album { [JsonProperty("albumName")] public string AlbumName { get; set; } }
3. Verify Postman Request Configuration
This is the most frequent culprit! Make sure your Postman request is set up correctly:
- Request Method: Select
POST - Content-Type Header: Add
Content-Type: application/jsonunder the Headers tab. Without this, ASP.NET Core can’t parse the JSON body. - Request Body: Switch to the "raw" tab, select
JSONfrom the dropdown, and use valid JSON:{ "AlbumName": "My Favorite Album" }
Avoid using form-data or x-www-form-urlencoded unless you’re intentionally binding from form fields (which isn’t typical for complex objects).
4. Confirm Newtonsoft.Json is Installed
.NET Core 2.0 uses Newtonsoft.Json by default for JSON serialization, but if it was accidentally removed, reinstall it via NuGet:
Install-Package Newtonsoft.Json -Version 11.0.2
Or add this to your .csproj file:
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
Quick Troubleshooting Tip
If you’re still stuck, check the ModelState in your controller—call ModelState.IsValid and inspect the errors. This will tell you exactly why binding failed (e.g., missing required properties, invalid JSON format).
内容的提问来源于stack exchange,提问作者Abhin Jose

