In this article I will explain with an example, how to send AntiForgeryToken with AngularJS AJAX request in ASP.Net CoreRazor Pages.
The AntiForgeryToken is used to prevent cross-site request forgery (CSRF) attacks and this article will illustrate how to configure and use the AntiForgeryToken during AngularJS AJAX request in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net Core Razor Pages, please refer my article ASP.Net Core Razor Pages: Hello World Tutorial with Sample Program example.
 
 
Configuring the Anti-Forgery Token and JSON Serializer setting
The first step is to configure the Anti-Forgery Token and JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
ASP.Net Core Razor Pages: Sending AntiForgeryToken with AngularJS AJAX request
 
2. Add the following namespace.
using Newtonsoft.Json.Serialization;
 
3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to:
1. Add MVC Services for Razor Pages.
2. Use Newtonsoft JSON for serialization.
3. Add Anti-Forgery Token with specific name to the Form.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
 
 
Model
Following is a Model class named PersonModel with two properties i.e. Name and DateTime.
public class PersonModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
 
    ///<summary>
    /// Gets or sets DateTime.
    ///</summary>
    public string DateTime { get; set; }
}
 
 
Razor PageModel (Code-Behind)
The PageModel consists of two 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 AngularJS AJAX operation
This Handler method handles the AJAX call made from the AngularJS $http service in the Razor Page.
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 object of PersonModel class is received as parameter and the Name property holds the value of the TextBox sent from the Razor Page.
Note: The FromBody attribute is used for model-binding the data sent from AngularJS $http service.
 
Finally, the Current DateTime of the Server is set into the DateTime property and the PersonModel object is returned to the Razor Page in JSON format.
public class IndexModel : PageModel
{
    public void OnGet()
    {
    }
 
    [ValidateAntiForgeryToken]
    public IActionResult OnPostGetTime([FromBody] PersonModel person)
    {
        person.DateTime = DateTime.Now.ToString();
        return new JsonResult(person);
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
The HTML DIV consists of an HTML TextBox and a Button. The Button has been assigned AngularJS ng-click directive. When the Button is clicked, the ButtonClick function is executed.
Note: If you want to learn more about ng-click directive, please refer my article AngularJS: Implement Button click event using ng-click directive example.
 
The Anti-Forgery Token has been added to Razor Page using the AntiForgeryToken function of the HTML Helper class.
Inside the ButtonClick function, the $http service is used to make an AJAX call to the Handler method.
The $http service has following properties and methods.
Properties
1. method – The method type of HTTP Request i.e. GET or POST.
2. url – URL of the Handler method. In this case /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.
 
3. datatype – The format of the data i.e. XML or JSON.
4. data – The parameters to be sent to the Handler method.
5. headers – List of headers to be specified for the HTTP Request.
The value of the Anti-Forgery Token is read from the Hidden Field added by the Html.AntiForgeryToken HTML Helper function and added to the headers property of $http service.
Note: Without passing Anti-Forgery Token, the AJAX call to the Handler method of the Razor PageModel will not work.
 
Event Handler
1. success – This event handler is triggered once the AJAX call is successfully executed.
2. error – This event handler is triggered when the AJAX call encounters an error.
The response from the AJAX call is received in JSON format inside the Success event handler of the $http service and the result is displayed using JavaScript Alert Message Box.
Note: If you want to learn more on displaying JavaScript alert with AngularJS, please refer my article AngularJS: Display (Show) JavaScript Alert box.
 
@page
@model AngularJS_Razor_Core.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http, $window) {
            $scope.ButtonClick = function () {
                var antiForgeryToken = document.getElementsByName("__RequestVerificationToken")[0].value;
                var post = $http({
                    method: "POST",
                    url: "/Index?handler=GetTime",
                    dataType: 'json',
                    data: { name: $scope.Name },
                    headers: {
                        "Content-Type": "application/json",
                        "XSRF-TOKEN": antiForgeryToken
                    }
                });
 
                post.success(function (data, status) {
                    $window.alert("Hello: " + data.Name + ".\nCurrent Date and Time: " + data.DateTime);
                });
 
                post.error(function (data, status) {
                    $window.alert(data.Message);
                });
            }
        });
    </script>
    @Html.AntiForgeryToken()
    <div ng-app="MyApp" ng-controller="MyController">
        Name:
        <input type="text" ng-model="Name" />
        <br/>
        <br/>
        <input type="button" value="Get Current Time" ng-click="ButtonClick()" />
    </div>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: Sending AntiForgeryToken with AngularJS AJAX request
 
 
Downloads