简体   繁体   English

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

[英]Angular 6 Post Request to .NET Core API

I am working with angular 6 trying to send a post request using httpclient , but always receive null body on the server side. 我正在使用angular 6尝试使用httpclient发送发帖请求,但始终在服务器端收到null正文。

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

and API function 和API功能

[HttpPost]
public List<Rule> AddTemplateTextRules( [FromBody]Rule[] Rules)
{
    try
    {
        return RuleManager.AddRule(Rules);
    }
    catch (Exception e)
    {
        return null;
    }
    return null; 
}

To make a post request in Angular 6 with standard practice you need to do followings: 要使用标准实践在Angular 6中发出发布请求,您需要执行以下操作:

In the service class: 在服务类中:

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

In the Component: 在组件中:

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

Then in the ASP.NET Core API Controller: 然后在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);
   }
}

Hope it will help you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM