我正在使用ASP.NET CORE,目前正在研究REST API。因此,我知道不同动词之间的区别,但是我无法向自己解释一件事。 如果我们有一个URL-/ customers / {id},并且正在使用它来获取和发布客户。如何判断是要阅读还是要创建新客户?
在控制器中,我可以这样做:
[HttpGet]
public IActionResult Customer(string id)
{
// not important
}
[HttpPost]
public IActionResult Customer(string id)
{
// not important
}
因此,我想创建一个新客户并使用/ customers / {John}。 如果它们都具有相同的参数,它将如何选择HttpPost而不是HttpGet?
答案 0 :(得分:1)
这是由API使用者指定的。既然您说的是您从网页上调用它,然后使用JavaScript fetch API举例说明。
POST示例:
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));