首页 文章

Angular 6 发布.NET 核心 API 请求

提问于
浏览
0

我正在使用 angular 6 尝试使用 httpclient 发送一个 post 请求,但总是在服务器端接收 null body。

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 回答

  • 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 核心 API 控制器中:

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

    希望它会对你有所帮助。

相关问题