LeonidasFett
LeonidasFett

Reputation: 3132

HttpClient.DeleteAsync with multiple parameters

I am trying to make a HttpDelete request have multiple parameters. I cannot use the body and I don't want to use HttpPost.

This is my action:

[HttpDelete("{ids}")]
public async Task Delete(int[] ids)
{
    foreach(int id in ids)
        await _repository.DeleteLogAsync(id);
}

And this is the code I use for sending the request:

public async Task DeleteLogs(int[] ids)
{
    var queryString = HttpUtility.ParseQueryString(string.Empty);
    foreach (var id in ids)
    {
        queryString.Add("id", id.ToString());
    }

    var url = _configuration["BaseUrl"] + _configuration["Endpoint"] + "/" + queryString.ToString();

    using (var httpClient = new HttpClient())
    {                
        var response = await httpClient.DeleteAsync(url);
        response.EnsureSuccessStatusCode();
    }
}

I also use Swagger and it shows me the following:

enter image description here

If I try sending the request exactly as it's shown above, I get a 415 response. I also find it weird that swagger expects two parameters, one in body and one in the query.

So I tried using [FromQuery] in my action. In this case, the request goes through but the int array is empty in my action. So I am kinda stuck and don't know how to proceed. As per this answer, it should work.

Can anyone tell me what I am doing wrong?

Upvotes: 0

Views: 7249

Answers (1)

Nkosi
Nkosi

Reputation: 246998

Remove the route template from the action and adorn the parameter with [FromQuery]

//DELETE {endpoint}?ids=value1&ids=value2&...
[HttpDelete()]
public async Task<IActionResult> Delete([FromQuery]int[] ids) {
    foreach(int id in ids)
        await _repository.DeleteLogAsync(id);

    return Ok();
}

and on the client construct the query string with the correct parameter name

static readonly Lazy<HttpClient> httpClient = new Lazy<HttpClient>();
public async Task DeleteLogs(int[] ids) {
    var queryString = new QueryString(string.Empty);
    foreach (var id in ids) {
        queryString.Add("ids", id.ToString());
    }

    var url = _configuration["BaseUrl"] + _configuration["Endpoint"] + "/" + queryString.ToString();

    var response = await httpClient.Value.DeleteAsync(url);
    response.EnsureSuccessStatusCode();        
}

Upvotes: 1

Related Questions