0

I'm trying to make a call to an MVC Web API using angular 2. The endpoint I have looks like this:

[HttpDelete]
[Route("DeleteMe")]
public ActionResult DeleteItems([FromQuery] string objectId, [FromBody] int[] toDelete) {
    //logic
}

And I can test this using postman, where I set a body using the content type 'application/json', and enter the following data.

[1,2,3]

This works just fine. However I cannot recreate this call with angular 2. I am using HttpClient to make my calls, and have code similar looking to this:

public callDeleteItems(objId: number, toDelete: number[]) {
    var serviceEndpoint = "endpoint here?objectId=" + objId;
    const params = new HttpParams().set("toDelete", JSON.stringify(toDelete));
    this.http.request('delete', serviceEndpoint, {
        params: params
    }).subscribe();
}
Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140
Stinkidog
  • 425
  • 2
  • 7
  • 19
  • Please take a look at this : https://stackoverflow.com/questions/16374954/passing-array-of-integers-to-webapi-method – Ramesh Rajendran Feb 16 '18 at 09:46
  • Much common scenario for DELETE is to have delete ids as query parameter ([FromUri]). Otherwise see @RameshRajendran link. – zhuber Feb 16 '18 at 09:48

1 Answers1

1

You have to use URLSearchParams

Something like this to generate your URL

public getURL(objId: number, toDelete: number[]): string {
    const urlParams: URLSearchParams = new URLSearchParams();
    urlParams.set('objectId', objId.toString());
    toDelete.forEach(n => urlParams.append('toDelete', n.toString()));
    return '/endpoint?' + urlParams.toString();
}

When you have to send an array, you have to use the append method

Example:

this.getURL(12, [1, 2, 3]);

Will generate the url as

/endpoint?objectId=12&toDelete=1&toDelete=2&toDelete=3

Your web API controller action should be

[HttpDelete]
[Route("DeleteMe")]
public ActionResult DeleteItems([FromUri] string objectId, [FromUri] int[] toDelete) {
    //logic
}

Demo

cyberpirate92
  • 3,076
  • 4
  • 28
  • 46