I currently not sure how to use a fetch post call to pass an object to a method expecting that object. I created a payload and passed it but does not seem to work. I have set a breakpoint in the code behind but it is never hit. Not sure why the fetch call is not working. Any suggestions on way the endpoint is not being reached?
This is my method in C#.
[HttpPost]
[Route("ResetPassword")]
private void ResetPassword(Player player){
{
Javascript:
const continueBtn = document.getElementById("continueBtn");
continueBtn.onclick = () => {
const email = document.getElementById("lblEmail").innerHTML;
sendResetEmail(email);
}
async function sendResetEmail(email) {
const payload = {
email: email
}
const data = new FormData();
data.append("json", JSON.stringify(payload));
let sendResetEmail = await fetch(`/ResetPassword`,
{
method: 'POST',
body: data
});
}
CodePudding user response:
if you don't want to provide the name of the parameter in your client, you need to give the [FromBody] attribute in your API:
[HttpPost]
[Route("ResetPassword")]
private void ResetPassword([FromBody] Player player){
}
Then, on the client, there are multiple ways, but the most common/modern is to use JSON encoding:
const payload = {
email: email
}
const data = JSON.stringify(payload);
let sendResetEmail = await fetch(`/ResetPassword`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
});
}