In this article I will explain with an example, how to send AntiForgeryToken with AJAX requests in ASP.Net Core (.Net Core 8) Razor Pages.
 
 
 

Configuring Anti-Forgery Token and JSON Serializer setting

The first step is to configure the Anti-Forgery Token and JSON Serializer settings in the Program.cs file.
Open the Program.cs class from the Solution Explorer window.
ASP.Net Core 8: Sending AntiForgeryToken with AJAX requests in Razor Pages
 
Then, you will have to add the following code which will instruct the program to:
1. Use JsonOptions for JSON Serializer.
2. Add Anti-Forgery Token with specific name to the Form.
var  builder = WebApplication.CreateBuilder(args);
 
// Add services to the container.
builder.Services.AddRazorPages()
       .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
 
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.Run();
 
 

Model

The Model class consists of following properties i.e. Name and DateTime.
public class PersonModel
{
    /// <summary>
    /// Gets or sets Name.
    /// </summary>
    public string Name { getset; }
 
    /// <summary>
    /// Gets or sets DateTime.
    /// </summary>
    public string DateTime { getset; }
}
 
 

Razor PageModel (Code-Behind)

The PageModel consists of following Handler methods.

Handler method for handling GET operation

This Handler method handles the GET calls, for this particular example it is not required and hence left empty.
 

Handler method for handling jQuery AJAX operation

This Handler method handles the call made from the jQuery AJAX function from the View.
Note: The following Handler method handles AJAX calls and hence the return type is set to JsonResult.
 

Attributes

ValidateAntiForgeryToken: The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Note: A cross-site request forgery is an attack is done by sending harmful script element, malicious command, or code from the user’s browser.
 
The value of the name parameter is assigned to the Name property of the PersonModel class object along with the Current DateTime.
Finally, the PersonModel class object is returned back as JSON to the jQuery AJAX function.
public class IndexModel : PageModel
{
    public void OnGet()
    {
    }
 
    [ValidateAntiForgeryToken]
    public IActionResult OnPostGetTime(string name)
    {
        PersonModel person = new PersonModel
        {
            Name = name,
            DateTime = DateTime.Now.ToString()
        };
        return new JsonResult(person);
    }
}
 
 

Razor Page (HTML)

HTML Markup

The HTML of Razor Page consists of following elements.
TextBox – For user input.
Button – For making AJAX call.
 
Inside the Razor Page, the following JS file is inherited.
1. jquery.min.js
 
Inside the jQuery document ready event handler, the Button has been assigned with a jQuery click event handler and when the Button is clicked a jQuery AJAX called is made to the Handler method.
The Anti-Forgery Token has been added to the Razor Page using the AntiForgeryToken function of the HTML Helper class.
The URL for the jQuery AJAX call is set to the Handler method of the Razor PageModel i.e. /Index?handler=GetTime.
Note: In the Razor PageModel, the Handler method name is OnPostGetTime but here it will be specified as GetTime when calling from the Razor HTML Page.
 
The value of the Anti-Forgery Token is read from the Hidden Field and passed as Request Header in the jQuery AJAX call.
Note: Without passing Anti-Forgery Token, the AJAX call to the Handler method of the Razor PageModel will not work.
 
The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
@page
@model Razor_jQuery_AJAX_8.Pages.IndexModel
@{
     Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.AntiForgeryToken()
    <input type="text" id="txtName" />
    <input type="button" id="btnGet" value="Get Current Time" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Index?handler=GetTime",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    data: {"name": $("#txtName").val() },
                    success: function (response) {
                        alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>
 
 

Screenshot

ASP.Net Core 8: Sending AntiForgeryToken with AJAX requests in Razor Pages
 
 

Downloads