簡體   English   中英

調用API Controller的delete方法不起作用

[英]Calling Delete Method of API Controller Does Not Work

GetPost方法工作正常,但是當我嘗試調用Delete端點時,它似乎從未執行過。

用戶控制器.cs

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

我正在使用HttpClient執行請求,如下所示:

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();
}

我創建了一個控制台應用程序來測試 API:

程序.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());
    }
}

當我使用 Postman 調用同一個端點時,它可以工作,我做錯了什么?

您正在嘗試從請求正文 ( [FromBody] ) 解析用戶名,但您沒有向 HTTP 客戶端提供任何有效負載,而是在 URL 中指定參數。 因此,您的 API 方法應如下所示:

用戶控制器.cs

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

下面的代碼將針對UserController發出DELETE請求,並將john-doe作為userName參數傳遞。

程序.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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM