In this article I will explain with an example, how to implement AntiForgery Token in Web API in ASP.Net Core MVC.
This article will explain how to make a jQuery POST call to Web API using jQuery AJAX in ASP.Net Core MVC.
Note: For beginners in ASP.Net Core MVC, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
What is Web API in .Net Core?
ASP.Net Core Web API is a framework to build HTTP services which can be consumed by cross platform clients including desktops or mobile devices irrespective of the Browsers or Operating Systems being used.
ASP.Net Core Web API supports RESTful applications and uses GET, PUT, POST, DELETE verbs for client communications.
Configuring the AntiForgery Token and JSON Serializer setting
The first step is to configure the AntiForgery Token and JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
Implement AntiForgery Token in ASP.Net Web API
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. Use Newtonsoft JSON for serialization.
2. Add AntiForgery Token with specific name to the Form.
public void ConfigureServices(IServiceCollection services)
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
Following is a Model class named PersonModel with two properties i.e. Name and DateTime.
public class PersonModel
    /// Gets or sets Name.
    public string Name { get; set; }
    /// Gets or sets DateTime.
    public string DateTime { get; set; }
Adding the Web API
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer select on Add and then Add New Item.
Now from the Add New Item window, choose the API Controller – Empty option as shown below.
Implement AntiForgery Token in ASP.Net Web API
Then give it a suitable name and click Add.
Web API Controller
The next step is to add an Action Method to the Web API Controller.
The Web API Controller consists of a method named AjaxMethod which accepts an object of PersonModel and updates the DateTime property with the Current Date and Time and returns it back.
Route: The Route attribute defines its Route for calling the Web API method.
HttpPost: The HttpPost attribute which signifies that the method will accept Http Post requests.
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.
public class AjaxAPIController : ControllerBase
    public PersonModel AjaxMethod(PersonModel person)
        person.DateTime = DateTime.Now.ToString();
        return person;
Now you will need to add one empty Controller along with a View. The View will be used for calling the Web API Controller’s method using jQuery AJAX.
The Controller consists of an empty Action method which simply returns the View.
public class HomeController : Controller
    // GET: Home
    public IActionResult Index()
        return View();
The View consists of an HTML TextBox element and a Button. The Button has been assigned a jQuery click event handler and when the Button is clicked a jQuery AJAX call is made to the Web API Controller’s method.
The AntiForgery Token has been added to the View using the AntiForgeryToken function of the HTML Helper class.
The URL for the jQuery AJAX call is set to the Web API Controller’s method i.e. /api/AjaxAPI/AjaxMethod.
The value of the AntiForgery Token is read from the Hidden Field and passed as Request Header in the jQuery AJAX call.
The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width" />
    <input type="text" id="txtName" />
    <input type="button" id="btnGet" value="Get Current Time" />
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                var person = '{Name: "' + $("#txtName").val() + '" }';
                    type: "POST",
                    url: "/api/AjaxAPI/AjaxMethod",
                    beforeSend: function (xhr) {
                    data: person,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
                    failure: function (response) {
                    error: function (response) {
Implement AntiForgery Token in ASP.Net Web API