A set of technologies in .NET for building web applications and web services. Miscellaneous topics that do not fit into specific categories.
Hello Joseph Kashishian,
Thanks for trying my solution. I see you tried adding AddAntiforgery from my answer, but you're mixing it with old .NET Core 2.1 syntax that doesn't exist in .NET 7. Here's the corrected version:
What's wrong with your code:
// ? This is .NET Core 2.1 syntax - doesn't exist in .NET 7
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1) // ? REMOVED in .NET 5+
.AddJsonOptions(...); // ? Wrong syntax for .NET 7
// ? This part is correct, but needs proper .NET 7 context
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
Correct .NET 7 version:
Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add Razor Pages
builder.Services.AddRazorPages();
// ? Configure antiforgery - this is what you tried to add
builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "RequestVerificationToken";
});
var app = builder.Build();
app.UseRouting();
app.MapRazorPages();
app.Run();
Razor Page (.cshtml):
@page
@model YourNamespace.Pages.AjaxPostModel
@{
ViewData["Title"] = "AjaxPost";
}
<h1>AjaxPost</h1>
<hr />
<form method="post">
<input type="text" id="name" placeholder="Enter name" />
<br />
<input type="text" id="datetime" placeholder="Enter datetime" />
<br />
</form>
<input type="button" id="ajaxPost" value="POST" />
<div id="result"></div>
@section Scripts {
<script>
document.getElementById("ajaxPost").addEventListener('click', async () => {
const token = document.querySelector('input[name="__RequestVerificationToken"]').value;
const result = document.getElementById("result");
const response = await fetch("/ajaxpost", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'RequestVerificationToken': token,
'X-Requested-With': 'XMLHttpRequest'
},
body: JSON.stringify({
name: document.getElementById("name").value,
datetime: document.getElementById("datetime").value
})
});
if (response.ok) {
const data = await response.text();
result.innerText = data;
} else {
result.innerText = `Error: ${response.status}`;
}
});
</script>
}
PageModel (.cshtml.cs):
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace YourNamespace.Pages
{
public class AjaxPostModel : PageModel
{
public void OnGet()
{
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult OnPost([FromBody] PersonModel model)
{
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return Content($"Name: {model.Name}, DateTime: {model.DateTime}");
}
return BadRequest();
}
}
public class PersonModel
{
public string Name { get; set; }
public string DateTime { get; set; }
}
}
Key changes from .NET Core 2.1 to .NET 7:
- No more
Startup.cs- everything inProgram.cs - Use
builder.Services.AddRazorPages()instead ofservices.AddMvc() - No more
SetCompatibilityVersion()- removed in .NET 5+ - Use
var builder = WebApplication.CreateBuilder(args)minimal hosting pattern
The AddAntiforgery you tried is correct, just needs to be in the right place with .NET 7 syntax. The key is reading the token from the hidden field and sending it in the RequestVerificationToken header with your JSON payload.
Hope this helps!