Search code examples
angularasp.net-coreasp.net-core-webapiangular12

How to transfer data via query params of a POST request, using Angular?


I am facing an annoying issue. When trying to pass data using HttpParams from Angular to backend (ASP.NET Core Web API), the backend parameters are all null. I am using Angular 12 version.

Here is my code:

Component.ts:

nn:string;
price = "200";
username = 700;
Id = 0;
...
tokenizeUserDetails() {
{
...
     
     let params = new HttpParams();
     params = params.append('Id', 0);
     params = params.append('nn', payload.nonce);
     params = params.append('price', this.price);
     params = params.append('username', this.username);
     console.log(params);
  
     this.http.post(this.baseUrl+ 'paypal',params).subscribe({
      next: response => { 
        console.log(this.CToken);
        this.CToken = response;
      },
...

Backend:

[Produces("application/json")]
public class paypalController : BaseApiController
{
   ...

    [HttpPost]
    public async Task <paypalDto> Create([FromQuery] paypalDto order)
    {
       // ...
    }
}

PaypalDto.cs:

public class paypalDto
{   public int  Id { get; set; }
    public string price { get; set; } 
    public string nn { get; set; }
    public int username { get; set; }
}

When I run the application and pass the data from Angular to the backend, all parameters are null:

enter image description here

But by using console.log() for testing purpose, I found correctly data in my browser console:

enter image description here

I have tried to pass by using fours parameters but Angular showed an error for overload purpose. That's why I am trying to pass those data using HttpParams but I am facing unexpected and annoying output. I am an absolute beginner. How to resolve this issue please help.


Solution

  • Solution 1: Pass data to API with query parameters.

    Since you want to send the request by passing data with query parameters, modify the API action to receive the query parameters with `[FromQuery] attribute.

    [HttpPost]
    public async Task <paypalDto> Create([FromQuery] int Id, [FromQuery] string price, [FromQuery] string nn, [FromQuery] int username)
    

    And append params object into httpOptions object. Pass the httpOptions object in post method.

    let params = new HttpParams();
    ...
    
    let httpOptions = {
      params: params
    };
    
    this.http.post(this.baseUrl+ 'paypal', null, httpOptions).subscribe(...);
    

    Solution 2: Post data to API with Request Body

    Since it is a POST method, you should utilize it to post data with the request body.

    [HttpPost]
    public async Task <paypalDto> Create([FromBody] paypalDto order)
    
    let obj = {
      Id: 0,
      nn: payload.nonce,
      price: this.price,
      username: this.username
    };
      
    this.http.post(this.baseUrl+ 'paypal', obj).subscribe(...);