using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Mvc;
namespace MyApp.Pages;
public class ListModel : PageModel
{
private readonly IAntiforgery _antiForgery;
public AntiforgeryTokenSet AntiForgeryToken {get; private set;}
public ListModel(
IAntiforgery antiForgery
)
{
this._antiForgery = antiForgery;
}
public async Task OnGet()
{
AntiForgeryToken = _antiForgery.GetAndStoreTokens(HttpContext);
}
public async Task<JsonResult> OnPostWafflesAsync(bool test)
{
System.Console.WriteLine("Test approval result="+test);
return new JsonResult(new {
received = true,
test,
});
}
}
<script>
const formData = new FormData();
formData.append('test', false);
fetch(
`${window.location}?handler=Waffles`,
{
method: "POST",
headers: {
RequestVerificationToken:`@Model.AntiForgeryToken.RequestToken`,
},
body: formData,
});
</script>
In this scenario, we are sending a JsonResult for easier consumption by JavaScript, although the example does not utilize the result.
Please note that in the script referenced above, the handler is Waffles
and not OnPostWafflesAsync
, related
References: