I have created a basic razor web project and defined it as follows: in program.cs I added
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
In the controller, this is what I did:
[Route("/api/[controller]")]
[ApiController]
public class BookController : ControllerBase
{
[HttpPost("SimplePost")]
public IActionResult SimplePost([FromForm] BookEntry entry)
{
var result = entry;
return Ok();
}
}
The class looks like this:
public class BookEntry
{
public int BookId { get; set; }
public string BookName { get; set; } = string.Empty;
}
And then on the view page,
@Html.AntiForgeryToken()
<form id="bookform">
<div class="row">
<div class="col">
<label for="BookId" class="form-label">Book Id</label>
<input type="text" name="BookId" class="form-control" />
</div>
<div class="col">
<label for="BookName" class="form-label">Book Name</label>
<input type="text" name="BookName" class="form-control" />
</div>
</div>
</form>
<div class="row mt-5">
<div class="col position-relative">
<div class="d-grid gap-2 d-md-block position-absolute bottom-0">
<button class="btn btn-outline-secondary" id="search__btn"><i class="fa fa-search fa-fw"></i>Post Buton A</button>
</div>
</div>
<div class="col position-relative">
<div class="d-grid gap-2 d-md-block position-absolute bottom-0">
<button class="btn btn-outline-secondary" id="search__btn2"><i class="fa fa-search fa-fw"></i>Post Buton B</button>
</div>
</div>
</div>
Where I create two buttons, so in the JavaScript code, I wrote the following :
<script>
$(function () {
var url = "/api/book/simplepost";
$("#search__btn").click(function (e) {
var formData = $("#bookform").serialize();
fetch(url, {
method: "POST",
body: formData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
})
.then(response => console.log("done"))
});
$("#search__btn2").click(function (e) {
var formData2 = $("#bookform").serialize();
$.ajax({
url: url,
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: formData2,
success: function (result, status, xhr) {
console.log(`success`);
},
error: function (xhr, status, error) {
console.log(`error`);
}
}).always(function () {
console.log(`always done`);
});
});
});
</script>
When I click Post Button A which uses fetch, it goes to the simplepost function, but the entry parameter inside is empty. When I click Post Button B, the console displays a 400 error even though I have added the header. Can someone help me fix this issue?
Thank you