RESTAPI Get和Post何时应该选择合适的API

RESTAPI Get和Post何时应该选择合适的API,rest,api,Rest,Api,我正在使用ASP.NET内核,目前正在学习RESTAPI。所以,我知道不同动词之间的区别,但我不能向自己解释一件事。 如果我们有一个URL-/customers/{id},并且我们使用它来获取和发布客户。它如何判断是阅读还是创建新客户 在控制器中,我可以有: [HttpGet] public IActionResult Customer(string id) { // not important }

我正在使用ASP.NET内核,目前正在学习RESTAPI。所以,我知道不同动词之间的区别,但我不能向自己解释一件事。 如果我们有一个URL-/customers/{id},并且我们使用它来获取和发布客户。它如何判断是阅读还是创建新客户

在控制器中,我可以有:

        [HttpGet]
        public IActionResult Customer(string id)
        {
            // not important
        }

        [HttpPost]
        public IActionResult Customer(string id)
        {
            // not important
        }
因此,我想创建一个新客户并使用/customers/{John}。
如果HttpPost和HttpGet具有相同的参数,它将如何选择HttpPost而不是HttpGet?

这是由API的使用者指定的。既然你说你是从一个网页调用它,那就用一个使用javascript API的例子来说明吧

帖子示例:

fetch("/customers/' + custId, {
  method: 'POST', 
  body: JSON.stringify(data), //data being your customer data
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
fetch("/customers/' + custId) //if not specified, fetch defaults to GET
.then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
获取示例:

fetch("/customers/' + custId, {
  method: 'POST', 
  body: JSON.stringify(data), //data being your customer data
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
fetch("/customers/' + custId) //if not specified, fetch defaults to GET
.then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

这是由前端或任何调用API的程序决定的。无论您使用的是curl、fetch、axios、httpie、您的浏览器,还是其他任何利用http协议进行读写的工具,都需要指定使用哪个http动词。如何调用API?这只是一个场景,假设我通过html页面调用这个/customers/{id},其中有{id}的输入。好的,我理解,谢谢。但是,我在哪里指定请求必须是POST,如果我是客户,我单击“创建客户”按钮,该按钮应连接到POST请求,这是如何发生的?如果我的参数与GET请求相同,那么服务器如何知道应该使用哪个http谓词呢?您可以将这些请求包装在一个函数中:getCustomerid和createCustomerdata。然后将“创建客户”按钮映射到后一个功能,例如onClick或onSubmit。通过执行此操作,单击CreateCustomer将向服务器端发送POST请求。在服务器端,该请求将由已经用[HttpPost]注释的函数处理。这就是这个注释的意思;它将只处理POST请求。完成了,我可以问一下,我们如何在ASP.NET中实现这一点?我相信,我是通过表单来实现的,就像//text一样,指定要发布的方法请求?当然,您可以使用表单。我不知道ASP.NET,但我假设这个解决方案不会特定于该框架。您在前端使用常规html和JavaScript,对吗?然后是的,您可以使用常规表单提交方法=postCheers mate!你帮了大忙!