对.NET Core API的Angular 6发布请求

时间:2018-07-27 22:34:57

标签: c# angular asp.net-core angular6

我正在使用angular 6尝试使用httpclient发送发布请求,但始终在服务器端接收到空正文。

 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; 
}

1 个答案:

答案 0 :(得分:4)

要使用标准实践在Angular 6中发出发布请求,您需要执行以下操作:

在服务类别中:

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
     });
   }
}

然后在ASP.NET Core API Controller中:

[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);
   }
}

希望它会对您有所帮助。