Search code examples
angularasp.net-web-apiasp.net-web-api2asp.net-web-api-routing

Custom route in Web Api 2 to call with angular app


So I have Web Api 2 set up and and doing my restful calls from Angular 5. I have a custom route that I would like to call but keep receiving a 400 error. Can someone shed a bit of light. Thanks.

Web API Side:

[Route("api/ViewAllRecords/GetApprovalRecords/{ upn }")]
public IQueryable GetViewAllRecordsForMgrApproval([FromBody]string upn)
{
    var set = db.ViewAllRecords.Where(record => record.ApproverUPN == 
     upn).AsQueryable();
    return db.ViewAllRecords;
}

Angular Side:

  GetRecordForApproval(upn) {
  return this.http.get(environment.apiUrl + '/ViewAllRecords/GetApprovalRecords', { params: {
      upn : upn
    }});
}

Solution

  • The action in question has a few issues with its definition.

    [FromBody] wont work with HTTP GET requests as they do not have a BODY

    //GET api/ViewAllRecords/GetApprovalRecords/upn_value_here
    [HttpGet]
    [Route("api/ViewAllRecords/GetApprovalRecords/{upn}")]
    public IQueryable GetViewAllRecordsForMgrApproval(string upn) {
        var set = db.ViewAllRecords.Where(record => record.ApproverUPN == upn).AsQueryable();
        return db.ViewAllRecords;
    }
    

    and secondly you have the upn in the route template which defines the URL but the client side is not calling a URL that would match the template.

    Update the URL called from the client

    GetRecordForApproval(upn) {
        var url = environment.apiUrl + '/ViewAllRecords/GetApprovalRecords/' + upn;
        return this.http.get(url);
    }