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

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:

1. Make sure your Angular request is actually being triggered (and configured correctly)

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.

2. Verify your Web API endpoint is set up to receive the request

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 incoming Bet parameter—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.

3. Debug with browser dev tools to see what's actually happening

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.post call, 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-Type is set to application/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# Bet class (note: C# uses PascalCase by default, while Angular uses camelCase—Web API should map these automatically, but double-check field names for typos).
4. Fix cross-origin (CORS) issues

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:

  1. Install the Microsoft.AspNet.WebApi.Cors NuGet package.
  2. 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
    }
}
5. Check service injection in Angular

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:39:28