How to send an array from angular 8 to web api core?

Viewed 4933

I have method in typeScript file:

searchUsers() {
    this.filterParams = [
        { parameterName: 'FirstName', filterOperator: 'Like', parameterValue: this.firstName },
        { parameterName: 'LastName', filterOperator: 'Like', parameterValue: this.lastName },
        { parameterName: 'UserName', filterOperator: 'Like', parameterValue: this.userName },
        { parameterName: 'Email', filterOperator: 'Like', parameterValue: this.email }
    ];
    this.service.getUsers(this.id, this.filterParams);
}

which calls service method:

getUsers(id, filterParams) {
  let params = new HttpParams()
    .set('id', id);
    .set('filterParams', filterParams);
  this.http.get(this.rootURL + '/user/getUsers', { params: params })
    .subscribe((res: any) => {
      this.users = res.users;
    };
  });
}

FilterParameter model in web api core is:

public class FilterParameter
{
    public string ParameterName;
    public FilterOperator FilterOperator;
    public string ParameterValue;
}

My web api core method is firing after click on search button in angular. This is my method in web api core:

[Route("getUsers/{id?}/{filterParams?}")]
[HttpGet]
public ActionResult GetUsers(int id, [FromQuery] List<FilterParameter> filterParams)
{
    try
    {
        _logger.LogInformation("Geting all users from the database");
        var users = _baseBL.GetUsers(id, filterModel);
        return Ok(new { users = users.Results, usersCount = users.RowCount});
    }
    catch (Exception ex)
    {
        _logger.LogError($"Something went wrong: {ex}");
        return StatusCode(500, "Internal server error");
    }
}

Id is good, but the problem is that my filterParams are empty list. Any idea why?

2 Answers

You should use HttpPost to achieve it.

Angular:

this.http.post(this.rootURL + '/user/getUsers/' + id, filterParams)
    .subscribe((res: any) => {
      this.users = res.users;
    };
});

.NET

[Route("getUsers/{id?}")]
[HttpPost]
public ActionResult GetMembersInGym(int gymId, [FromBody] List<FilterParameter> filterParams)
{
 ...
}

To use Get, use FromUri try like this:

public ActionResult GetUsers(int id, [FromUri] List<FilterParameter> filterParams)
{
}

First your id should be appended with url as params and second to send the query params use {params:yourparamsobject} so your code should be

  getUsers(id, filterParams) {
      let params = {filterParams:filterParams};
      this.http.get(this.rootURL + '/user/getUsers'+id, { params: params })
        .subscribe((res: any) => {
          this.users = res.users;
        };
      });
    }

Also notice in your api model FilterOperator is of type FilterOperator and on ui you are sending and string so either change FilterOperator to type string on api or change filterOperator to match the type on ui

Related