【问题标题】:Calling Delete Method of API Controller Does Not Work调用 API 控制器的删除方法不起作用
【发布时间】:2019-04-04 11:32:38
【问题描述】:

GetPost 方法工作正常,但是当我尝试调用 Delete 端点时,它似乎永远不会执行。

UserController.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:

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

当我使用 Postman 调用同一个端点时它可以工作,我做错了什么?

【问题讨论】:

  • 什么不执行?发生什么了?你能分享你其他有效的电话吗? .NET 可能会通过与 Postman 不同的代理,并且 .NET 使用的代理会阻止 HTTP DELETE 请求
  • 当我调用帖子或获取API中的断点时,删除没有任何反应,没有异常并且没有命中断点
  • 客户端会发生什么?你也能调试一下吗?
  • 我可以调试并且当我执行行 var result = await Client.DeleteAsync... 它只是执行并且我在 reutrn 结果上有一个断点...它永远不会被命中并且断点在从未被击中的正在运行的api。但是如果我从邮递员那里调用它,那么 api 中的断点就会被命中

标签: c# asp.net-core httpclient


【解决方案1】:

您正在尝试从请求正文 ([FromBody]) 中解析用户名,但您没有向 HTTP 客户端提供任何有效负载,而是在 URL 中指定参数。因此,您的 API 方法应如下所示:

UserController.cs

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

以下代码将针对UserController 发出DELETE 请求,并将john-doe 作为userName 参数传递。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-26
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多