You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular+ASP Core项目中FromBody参数始终为null问题求助

Troubleshooting [FromBody] Parameter Being Null in Angular + ASP.NET Core

Hey there! Let’s break down why your [FromBody] parameter keeps coming up null—especially since other requests work perfectly fine. This is a super common snag, so let’s walk through the most likely fixes step by step:

1. Double-Check JSON <-> Model Property Matching

First up, make sure the JSON your Angular app sends lines up exactly with your C# model’s properties. Here’s what to watch for:

  • Case sensitivity: By default, ASP.NET Core maps camelCase JSON fields (like userName) to PascalCase C# properties (like UserName). But if you’ve customized JSON serialization settings (e.g., disabled automatic case mapping), you’ll need to match the exact casing.
  • JsonPropertyName attributes: If your model uses [JsonPropertyName("customName")], your JSON must use customName as the field name—no exceptions.
  • Type mismatches: If your model has an int Age property, sending a string like "30" (instead of the number 30) will cause deserialization to fail, resulting in a null model.

2. Verify the Request’s Content-Type Header

Angular’s HttpClient sets Content-Type: application/json by default, but if you’ve modified headers or are using FormData by accident, ASP.NET Core won’t parse the body as JSON. To confirm:

  • Open your browser’s DevTools → Network tab → Find your POST request → Check the "Request Headers" section for Content-Type: application/json.
  • If it’s missing, explicitly set it in your Angular request:
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    
    // ...
    
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    this.http.post('/api/your-endpoint', yourPayload, { headers }).subscribe(...);
    

3. Avoid Double Serialization in Angular

Don’t manually call JSON.stringify() on your payload before sending it! The HttpClient.post() method automatically serializes JavaScript objects to JSON. If you double-serialize, you’ll send a string instead of a JSON object, and ASP.NET Core can’t map that to your model—resulting in null.

❌ Bad:

this.http.post('/api/endpoint', JSON.stringify(yourPayload));

✅ Good:

this.http.post('/api/endpoint', yourPayload);

4. Check ASP.NET Core Serialization Settings

If you’ve tweaked JSON serialization in your Program.cs or Startup.cs, that might be throwing things off. For example, if you disabled automatic camelCase mapping:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = null; // Disables camelCase mapping
    });

In this case, your Angular app must send JSON fields that exactly match your C# model’s PascalCase property names (e.g., UserName instead of userName).

5. Ensure Correct Controller Method Setup

Make sure your controller method follows these rules:

  • Only one parameter marked with [FromBody] (ASP.NET Core can only bind one JSON body to a parameter).
  • The [FromBody] attribute is applied to the correct parameter.

Example of a correct setup:

[HttpPost("submit-data")]
public IActionResult SubmitData([FromBody] YourCustomModel model)
{
    if (!ModelState.IsValid)
    {
        // Even if model isn't null, check validation errors here
        return BadRequest(ModelState);
    }
    // ... rest of your logic
}

6. Validate Request Body Format

Use your browser’s DevTools to inspect the raw "Request Payload" of your POST request. Look for:

  • Empty payloads (obviously, no data means null model).
  • Invalid JSON syntax (e.g., missing quotes around keys, trailing commas). Even small syntax errors will cause ASP.NET Core to fail deserialization.

Quick Diagnostic Steps

If you’re still stuck, try these quick checks:

  1. Send a minimal test payload with just one required field to see if it binds correctly.
  2. Temporarily remove validation attributes from your model to rule out validation failures causing issues.
  3. Check your model’s constructor—if it has required parameters that aren’t provided in the JSON, ASP.NET Core can’t instantiate it, resulting in null.

内容的提问来源于stack exchange,提问作者Lucas Arruda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:21:29