.NET API无法接收Angular 2请求体,如何配置Content-Type与跨域?
Hey Vijay, let's break down the issues you're facing and fix them step by step:
1. Mismatched Request Body Format (Core Problem)
The root cause of your model binding failure is that your Angular code wraps a single Contact object into an array (with contact.push(Body)), but your WebAPI endpoint expects a single Contact instance, not an array. The JSON payload shape doesn't match what the API is looking for.
Fix for Angular Code
Modify both of your POST methods to send the single Contact object directly, without wrapping it in an array:
Updated PostMethod:
PostMethod(URL, Body){ let url : string; url = _App._URL + URL; this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); // Remove the Access-Control-Allow-Origin header here – this is a server-side response header, not a client request header console.log(JSON.stringify(Body)); // Now this logs a single Contact object, not an array console.log(url); console.log(this.headers); return this._http.post(url, JSON.stringify(Body), {headers: this.headers}) .map((res: Response) => { if (res) { return [{ status: res.status, json: res.json() }] } }); }
Updated PostMethod2:
PostMethod2(URL,Body){ let url:string; url = _App._URL + URL; this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); // Remove Access-Control-Allow-Origin from request headers this.requestoptions = new RequestOptions({ method: RequestMethod.Post, url: url, headers: this.headers, body: JSON.stringify(Body), // Send the single object directly responseType : ResponseContentType.Json, }) return this._http.request(new Request(this.requestoptions)) .map((res: Response) => { if (res) { return [{ status: res.status, json: res.json() }] } }); }
2. Fix Incorrect CORS Header Handling
Access-Control-Allow-Origin is a server-side response header, not something you add to client requests. Including it in your Angular headers doesn't help and can even cause preflight request failures.
Set Up CORS in .NET WebAPI
To resolve cross-origin issues properly:
- Install the CORS NuGet package:
Install-Package Microsoft.AspNet.WebApi.Cors - Enable CORS in your
WebApiConfig.cs:using System.Web.Http; using System.Web.Http.Cors; public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Allow all origins, methods, and headers (restrict to specific origins in production!) var corsPolicy = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(corsPolicy); // Existing route configuration config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
The server will now automatically return the correct Access-Control-Allow-Origin header for cross-origin requests.
3. Ensure WebAPI Model Binding Works
Add the [FromBody] attribute to your API parameter to explicitly tell WebAPI to bind the model from the JSON request body:
[Route("SaveContact")] [HttpPost] public bool SaveContact([FromBody] Contact contact) // Add [FromBody] here { if (contact == null) { // Optional: Add logging here to debug if the model is still null return false; } var result = _context.Contact.Add(contact); _context.SaveChanges(); // Don't forget to persist changes to the database! return result != null; // Fixed the logic here – return true if the contact was added successfully }
4. Verify the Request in Browser DevTools
After making these changes, open your browser's DevTools (F12), go to the Network tab, and check the POST request:
- Confirm
Content-Typein the request headers is set toapplication/json - Check the Request Payload to ensure it's a single Contact object in JSON format, not an array
These fixes should resolve both the model binding failure and CORS-related issues.
内容的提问来源于stack exchange,提问作者vijay sahu

