MicroMan
MicroMan

Reputation: 2098

Calling Delete Method of API Controller Does Not Work

The Get and Post methods work fine, but when I try to call the Delete endpoint, it seems like it is never executed.

UserController.cs

[HttpDelete]
[MapToApiVersion("1.0")]
public async Task<IActionResult> Delete([FromForm] string userName)
{
    return await RemoveUser(userName);
}

I am using the HttpClientto perform the request as follows:

using (Client = new HttpClient())
{
    Client.BaseAddress = new Uri("https://localhost:44332/");
    var result = await Client.DeleteAsync(new Uri($"/api/v{Version}/User" +"/xxx"));
    return result.ToString();
}

I have created a console application to test the API:

Program.cs

public class Program
{
    private static readonly HttpClient Client = new HttpClient { BaseAddress = new Uri("https://localhost:44332/") };

    public static void Main(string[] args)
    {
        Task.Run(() => RunAsync(args));
        Console.ReadLine();
    }

    private static async Task RunAsync(IReadOnlyList<string> args)
    {
        var result = await Client.DeleteAsync(new Uri($"/api/v1/user/gareth"));
        Console.WriteLine(result.ToString());
    }
}

When I call the same endpoint using Postman it works, what am I doing wrong?

Upvotes: 3

Views: 1489

Answers (1)

prd
prd

Reputation: 2311

You are trying to parse the username from the request body ([FromBody]), but you are not providing any payload to the HTTP client, instead you are specifying the parameter within the URL. Therefore, your API method should look something like this:

UserController.cs

[HttpDelete("{userName}")]
public async Task<IActionResult> Delete(string userName)
{
    return await RemoveUser(userName);
}

The code below will issue a DELETE request against the UserController and pass john-doe as the userName parameter.

Program.cs

private static void Main(string[] args)
{
    var httpClient = new HttpClient { BaseAddress = new Uri("https://localhost:44332") };
    httpClient.DeleteAsync(new Uri("/api/v1/user/john-doe", UriKind.Relative)).Wait();
}

Upvotes: 1

Related Questions