C# Angular 6对.NET核心API的Post请求

C# Angular 6对.NET核心API的Post请求,c#,angular,asp.net-core,angular6,C#,Angular,Asp.net Core,Angular6,我正在使用angular 6尝试使用httpclient发送post请求,但总是在服务器端接收空正文 save( rules:RuleModel[]){ let _headers: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' }); return this._httpClient.post(AppConfig.BaseUrl,JSON.stringify(rules

我正在使用angular 6尝试使用httpclient发送post请求,但总是在服务器端接收空正文

 save( rules:RuleModel[]){

let _headers: HttpHeaders = new HttpHeaders({
  'Content-Type': 'application/json; charset=utf-8' 
});

return this._httpClient.post(AppConfig.BaseUrl,JSON.stringify(rules), {headers:_headers} );   } 
和API函数

[HttpPost]
public List<Rule> AddTemplateTextRules( [FromBody]Rule[] Rules)
{
    try
    {
        return RuleManager.AddRule(Rules);
    }
    catch (Exception e)
    {
        return null;
    }
    return null; 
}
[HttpPost]
公共列表AddTemplateTextRules([FromBody]规则[]规则)
{
尝试
{
返回RuleManager.AddRule(规则);
}
捕获(例外e)
{
返回null;
}
返回null;
}

要按照标准惯例在Angular 6中发出post请求,您需要执行以下操作:

在服务类中:

import {throwError,  Observable } from 'rxjs';
import {catchError} from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { Rule } from 'path';

@Injectable()
export class RuleService {
    constructor(private httpClient: HttpClient) { }
    private baseUrl = window.location.origin + '/api/Rule/';

    createTemplateTextRules(rules: Rules[]): Observable<boolean> {
       const body = JSON.stringify(rules);
       const headerOptions = new HttpHeaders({ 'Content-Type': 'application/json' });
       return this.httpClient.post<boolean>(this.baseUrl + 'AddTemplateTextRules', body, {
              headers: headerOptions
       }).pipe(catchError(this.handleError.bind(this));
    }

   handleError(errorResponse: HttpErrorResponse) {
     if (errorResponse.error instanceof ErrorEvent) {
        console.error('Client Side Error :', errorResponse.error.message);
     } else {
       console.error('Server Side Error :', errorResponse);
     }

    // return an observable with a meaningful error message to the end user
    return throwError('There is a problem with the service.We are notified & 
     working on it.Please try again later.');
   }
}
export class RuleComponent implements OnInit { 
    constructor(private ruleService: RuleService) { }
    createTemplateTextRules(): void {

    this.ruleService.createTemplateTextRules(rules).subscribe((creationStatus) => {
      // Do necessary staff with creation status
     }, (error) => {
      // Handle the error here
     });
   }
}
[Produces("application/json")]
[Route("api/Rule/[action]")]
public class RuleController : Controller
{
   [HttpPost]
   public Task<IActionResult> AddTemplateTextRules( [FromBody]Rule[] Rules)
   {
       try
       {
           return RuleManager.AddRule(Rules);
       }
       catch (Exception e)
       {
            return false;
       }
       return Json(true);
   }
}
然后在ASP.NET核心API控制器中:

import {throwError,  Observable } from 'rxjs';
import {catchError} from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { Rule } from 'path';

@Injectable()
export class RuleService {
    constructor(private httpClient: HttpClient) { }
    private baseUrl = window.location.origin + '/api/Rule/';

    createTemplateTextRules(rules: Rules[]): Observable<boolean> {
       const body = JSON.stringify(rules);
       const headerOptions = new HttpHeaders({ 'Content-Type': 'application/json' });
       return this.httpClient.post<boolean>(this.baseUrl + 'AddTemplateTextRules', body, {
              headers: headerOptions
       }).pipe(catchError(this.handleError.bind(this));
    }

   handleError(errorResponse: HttpErrorResponse) {
     if (errorResponse.error instanceof ErrorEvent) {
        console.error('Client Side Error :', errorResponse.error.message);
     } else {
       console.error('Server Side Error :', errorResponse);
     }

    // return an observable with a meaningful error message to the end user
    return throwError('There is a problem with the service.We are notified & 
     working on it.Please try again later.');
   }
}
export class RuleComponent implements OnInit { 
    constructor(private ruleService: RuleService) { }
    createTemplateTextRules(): void {

    this.ruleService.createTemplateTextRules(rules).subscribe((creationStatus) => {
      // Do necessary staff with creation status
     }, (error) => {
      // Handle the error here
     });
   }
}
[Produces("application/json")]
[Route("api/Rule/[action]")]
public class RuleController : Controller
{
   [HttpPost]
   public Task<IActionResult> AddTemplateTextRules( [FromBody]Rule[] Rules)
   {
       try
       {
           return RuleManager.AddRule(Rules);
       }
       catch (Exception e)
       {
            return false;
       }
       return Json(true);
   }
}
[产生(“应用程序/json”)]
[路线(“api/规则/[行动]”)]
公共类RuleController:控制器
{
[HttpPost]
公共任务AddTemplateTextRules([FromBody]规则[]规则)
{
尝试
{
返回RuleManager.AddRule(规则);
}
捕获(例外e)
{
返回false;
}
返回Json(true);
}
}

希望它能帮助您。

不要将未绑定的方法作为回调传递。请告诉我详细信息。
catchError(this.handleError)
很糟糕。如果
handleError
引用了该类的任何其他成员,它将失败。使用自由普通函数、箭头函数或
。将其绑定到
。要了解更多信息,请阅读
这个
如何在JavaScript中工作。这是我发送给服务器的对象有一些错误值的问题。但是现在我可以在服务器上接收列表了。非常感谢,我刚刚接触angular 2,这就是为什么我觉得有些事情我不明白,很高兴听到你的问题已经解决了!请点击“检查”图标接受正确答案,以便帮助其他人解决类似问题。非常感谢。