Angular 5与C# WebApi问题:POST请求未发送或后端未接收
Hey there, let's work through why your Angular 5 POST request isn't making it to your C# Web API (or isn't being picked up properly). Here are the key things to check and fix step by step:
First off, Angular's @angular/http uses cold observables—you have to subscribe to the request for it to fire. This is one of the most common mistakes! If your code calls http.post but doesn't add a .subscribe() block, the request will never leave the browser.
Here's how your service method should look (with proper headers and subscription):
// In your service class addBet(bet: Bet): Observable<Response> { const apiUrl = `${AppConfig.apiUrl}/bet`; const headers = new Headers({ 'Content-Type': 'application/json' }); const options = new RequestOptions({ headers: headers }); // Important: return the observable, and subscribe where you call this method return this.http.post(apiUrl, bet, options); } // In your component this.yourService.addBet(yourBetObject) .subscribe( (response) => { console.log('Request succeeded!', response); // Handle success (e.g. refresh data, show notification) }, (error) => { console.error('Request failed:', error); // Handle error (e.g. show error message) } );
Also double-check that HttpModule is imported in your AppModule—without it, Angular can't inject the Http service.
Your C# Web API needs two critical things to correctly handle the POST:
- A
[HttpPost]attribute on the method, plus a matching route that aligns with your Angular request URL. - The
[FromBody]attribute on the incomingBetparameter—this tells Web API to pull the data from the request body (not the URL).
Example of a correctly configured endpoint:
using System.Web.Http; public class BetsController : ApiController { [HttpPost] [Route("api/bet")] // Match this to the URL your Angular app is calling public IHttpActionResult AddBet([FromBody] Bet bet) { if (bet == null) { return BadRequest("Bet data is missing or invalid"); } // Your database logic here (add bet to DB) return Ok(bet); } }
If you don't include [FromBody], Web API will default to trying to get the parameter from the URL, and your bet object will be null.
Open your browser's Developer Tools (F12) and go to the Network tab. Trigger the action that should send the POST request, then look for the request entry:
- If no request shows up: Your Angular code isn't reaching the
http.postcall, or you forgot to subscribe. Check for conditional logic that might be blocking the request, or typos in method names. - If the request shows up:
- Check the Status Code: 404 means your URL is wrong; 400 means the request body is invalid; 500 means there's a server-side error.
- Check the Request Headers: Ensure
Content-Typeis set toapplication/json—if it's missing or set to something else, Web API can't parse the body. - Check the Request Body: Make sure the JSON matches the structure of your C#
Betclass (note: C# uses PascalCase by default, while Angular uses camelCase—Web API should map these automatically, but double-check field names for typos).
If your Angular app is running on a different port/domain than your Web API (e.g., Angular on localhost:4200, API on localhost:5000), the browser will block the request unless you enable CORS on the server.
To fix this in Web API:
- Install the
Microsoft.AspNet.WebApi.CorsNuGet package. - Add CORS configuration to 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 for testing—restrict to your frontend domain in production! var corsSettings = new EnableCorsAttribute("http://localhost:4200", "*", "*"); config.EnableCors(corsSettings); // Your other route configuration here } }
Make sure your service class is properly registered in your Angular module's providers array—if it's not, the service won't be injected correctly, and calling its methods will do nothing.
Example in AppModule:
import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { YourBetService } from './path-to-your-service'; @NgModule({ imports: [HttpModule], providers: [YourBetService], // ... other declarations/exports }) export class AppModule { }
内容的提问来源于stack exchange,提问作者karoluS

