Angular 5向.NET Core 2发送POST请求时Payload为空求助
Hey there! Let's dig into why your Angular 5 POST request's payload isn't making it to your .NET Core 2 API's auth controller. This is a super common gotcha, so let's break down the most likely culprits and fixes step by step.
1. First: Check Your Angular Request's Content-Type Header
.NET Core's API controllers expect JSON payloads to have the Content-Type: application/json header by default. While Angular's HttpClient usually sets this automatically when you pass a plain object, it's easy to accidentally override it or use the wrong format.
Here's a correct example of an Angular registration service method:
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { RegisterDto } from './your-dto-path'; @Injectable() export class AuthService { private baseUrl = '/api/auth'; // Explicitly set JSON headers (redundant for plain objects, but safe to confirm) private httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; constructor(private http: HttpClient) { } register(user: RegisterDto) { // Make sure you're passing the DTO directly, not wrapping it in an extra object return this.http.post(`${this.baseUrl}/register`, user, this.httpOptions); } }
Avoid using application/x-www-form-urlencoded unless you've configured your backend to handle form data (using [FromForm] instead of [FromBody] on your DTO parameter).
2. Verify .NET Core Controller Binding
Your auth controller needs to explicitly tell .NET where to pull the payload from. For JSON bodies, use the [FromBody] attribute on your DTO parameter. Also, double-check that your DTO's property names match what Angular is sending (case sensitivity matters unless you configure camel-case matching).
Example Controller Code:
[Route("api/auth")] [ApiController] public class AuthController : ControllerBase { [HttpPost("register")] public async Task<IActionResult> Register([FromBody] RegisterDto registerDto) { // First, check if model binding failed (this will tell you exactly what's wrong) if (!ModelState.IsValid) { var errors = ModelState.Values.SelectMany(v => v.Errors) .Select(e => e.ErrorMessage); return BadRequest(new { Errors = errors }); } // Rest of your registration logic... } }
Fix Case Mismatch (CamelCase vs PascalCase):
Angular typically sends camelCase properties (e.g., email, password), while .NET DTOs often use PascalCase (e.g., Email, Password). To make .NET automatically map these, add this configuration in your Startup.cs:
// For .NET Core 2, using Newtonsoft.Json (default) services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); });
3. Inspect the Actual Payload Being Sent
Open your browser's DevTools (Network tab), find the POST request to /api/auth/register, and check the Payload tab. Ask yourself:
- Does the payload structure exactly match your
RegisterDto? No extra nested objects (like wrapping everything in auserproperty)? - Are all required properties present and spelled correctly?
- Is any property set to
undefinedornullwhen it shouldn't be?
If the payload looks wrong, trace back to how you're constructing the RegisterDto object in Angular—maybe you're missing a property or assigning values incorrectly.
4. Check for ModelState Errors
As shown in the controller example above, returning ModelState errors will give you precise feedback about why binding failed. For example, if a required Email property is missing from the payload, the error message will tell you exactly that.
In Angular, catch the error to see these details:
this.authService.register(userData).subscribe( response => console.log('Success!', response), error => console.error('Registration failed:', error.error.Errors) );
Final Quick Checks
- Ensure your Angular app isn't accidentally sending a
FormDataobject instead of a plain JSON object (unless your backend is set up for form data). - Confirm CORS is configured correctly in .NET Core—while this usually blocks the request entirely, misconfigured CORS can sometimes lead to unexpected payload issues.
Start with these steps, and you'll almost certainly find the root cause of your empty DTO issue!
内容的提问来源于stack exchange,提问作者Rodney Wormsbecher

