使用FromBody特性绑定参数时父类属性无法赋值的问题
Hey there! Great question—inheritance absolutely works with model binding in ASP.NET Core, so this is almost certainly a serialization/naming convention mismatch rather than an inheritance limitation. Let's break down what's going on and how to fix it:
Why RowVersion is Always 0
By default, ASP.NET Core uses System.Text.Json for serialization/deserialization, which follows the camelCase naming convention. That means your C# property RowVersion (PascalCase) expects the JSON payload to have a matching rowVersion (lowercase first letter) field. If your request payload uses RowVersion instead, the serializer won't map it correctly, leaving the property at its default value of 0.
Another quick check: make sure you haven't accidentally added [JsonIgnore] or similar attributes to the RowVersion property in your BaseModel—that would also prevent binding.
Solutions to Fix the Binding
1. Adjust the Request Payload to Match CamelCase
Update your JSON request body to use rowVersion instead of RowVersion:
{ "name": "John Doe", "rowVersion": 123 }
This is the most straightforward fix and aligns with the default ASP.NET Core conventions.
2. Configure Serializer to Use PascalCase
If you need to keep using RowVersion in your request payload, you can configure the JSON serializer to respect the PascalCase property names from your C# classes.
For System.Text.Json (Default in ASP.NET Core 3.0+)
Add this configuration to your Program.cs file:
builder.Services.AddControllers() .AddJsonOptions(options => { // Disable camelCase naming policy to use exact property names options.JsonSerializerOptions.PropertyNamingPolicy = null; });
For Newtonsoft.Json (Json.NET)
If you're using Newtonsoft.Json instead (common if you migrated from older ASP.NET versions), configure it like this:
builder.Services.AddControllers() .AddNewtonsoftJson(options => { // Use default contract resolver to preserve PascalCase options.SerializerSettings.ContractResolver = new DefaultContractResolver(); });
3. Explicitly Map the Property Name with Attributes
If you only need to adjust this one property (and keep camelCase for others), you can use the [JsonPropertyName] attribute (for System.Text.Json) or [JsonProperty] (for Newtonsoft.Json) on the RowVersion property:
System.Text.Json:
public class BaseModel { [JsonPropertyName("RowVersion")] public int RowVersion { get; set; } }
Newtonsoft.Json:
public class BaseModel { [JsonProperty("RowVersion")] public int RowVersion { get; set; } }
Final Check
Double-check that your BaseModel's RowVersion property is public with both get and set accessors (which it is in your code snippet)—private/protected properties won't be bound by default.
Inheritance doesn't break model binding here—this is just a common naming convention pitfall! Any of these solutions should get your RowVersion property binding correctly.
内容的提问来源于stack exchange,提问作者Link69

