0

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?

1
  • 1
    Use a sniffer with the c# code and compare to the swagger results. Look at the headers and see if c# headers match swagger. Commented Sep 5, 2019 at 15:43

1 Answer 1

1

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();        
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.