【问题标题】:Delete request without id parameter in .net webApi在.net webApi中删除没有id参数的请求
【发布时间】:2019-04-29 03:15:47
【问题描述】:

我有如下所示的 .net 核心 WebApi。它运行良好。但是,当我写 [HttpDelete] 而不是 [HttpDelete("{id}")] 时,它就不起作用了。可能是什么原因?

我的网址:http://localhost:5004/api/Student/DeleteStudent/23

[ApiController]
[Route("api/[controller]/[action]")]
public class StudentController : ControllerBase
{
    //[HttpDelete] ///////////////// This is not working
    [HttpDelete("{id}")] /////////// This is working
    public async Task<ServiceResult> DeleteStudent(int id)
    {
      return await studentService.DeleteStudent(id);
    }
}

【问题讨论】:

  • MVC 如何知道从哪里获取 ID?为什么要移除路由模板?
  • 我只发送一个参数。我想,它可以知道@PanagiotisKanavos
  • 例如在本站; c-sharpcorner.com/article/…@PanagiotisKanavos 他没有使用 id 参数。
  • 没有 id 路由模板参数,只有其他填充值的方法是通过查询字符串(即http://localhost:5004/api/Student/DeleteStudent?id=23)。无论哪种方式,都需要提供 id 才能知道要删除哪条记录
  • 谢谢@Nkosi。我想,这就是我要找的。有效。你能写为答案,我会标记为答案。

标签: c# angular asp.net-web-api


【解决方案1】:

您必须告诉路由器您的 api 签名。现在通过将 [HttpDelete("{id}")] 替换为 [HttpDelete] 您的签名变为 api/[controller]/[action],因此您的路由器将忽略该签名之后的任何内容。

如果您想将其保留为[HttpDelete],您可以定义自定义路由,您还将在其中指定 id 作为参数。

【讨论】:

  • 谢谢@MichelHanna。 Nkosi 的回答解决了我的问题。
【解决方案2】:

如果没有{id} 路由模板参数,填充值的唯一其他方法是通过查询字符串

http://localhost:5004/api/Student/DeleteStudent?id=23 

路由表会将querystring参数匹配到action参数以进行匹配。

无论哪种方式,都需要提供id 以了解要调用哪个操作以及要删除哪个记录。

【讨论】:

    猜你喜欢
    • 2016-01-10
    • 1970-01-01
    • 2016-09-06
    • 2017-01-29
    • 1970-01-01
    • 2011-02-05
    • 2023-03-27
    • 2019-08-24
    • 2016-02-06
    相关资源
    最近更新 更多