In this article I will explain with an example, what is a Web API, why do we use it and how to use it 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 7, please refer my article ASP.Net Core 7: 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.
 
 

Model

The Model class consists of the following properties.
public class PersonModel
{
    public string Name { getset; }
    public string DateTime { getset; }
}
 
 

Web API Controller

In order to add a Web API Controller, you will need to Right Click the Controllers Folder (Directory) in the Solution Explorer and click on Add and then Controller.
Now from the Add New Scaffolded Item window, click on the Common option and select the API Controller – Empty option as shown below.
What is Web API, why to use it and how to use it in ASP.Net Core
 
Then in the Add New Item dialog window, select the API Controller – Empty option.
What is Web API, why to use it and how to use it in ASP.Net Core
 
Finally, give it a suitable name and click on Add button.
 
The Web API Controller consists of following Action method.

Action method for handling POST operation

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 class and updates the DateTime property with the Current Date and Time and returns it back.
This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept HttpPost request.
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.
 
[Route("api/[controller]")]
[ApiController]
public class AjaxAPIController : ControllerBase
{
    [Route("AjaxMethod")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public PersonModel AjaxMethod(PersonModel person)
    {
        person.DateTime = DateTime.Now.ToString();
        return person;
    }
}
 
 

Controller

The Controller consists of following Action method.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}
 
 

View

The HTML of the View consists of:
TextBox – For capturing Name.
Button – For displaying captured Name with Current Date Time.
The Anti-Forgery Token has been added to the View page using the AntiForgeryToken function of the HTML Helper class.
Note: The AntiForgeryToken function generates a HiddenField with the AntiForgery Token.
 
Inside the View, the following jQuery script file is inherited.
1. jquery.min.js
 
Inside the document ready event handler, the Button has been assigned with a jQuery click event handler.
Inside the click event handler, a jQuery AJAX call is made to the Web API Controller’s method.
The value of the AntiForgeryToken is read from the Hidden Field and passed as RequestHeader in the jQuery AJAX call.
Finally, the value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
@{
    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 () {
                var person = '{ "Name" : "' + $("#txtName").val() + '" }';
                $.ajax({
                    type: "POST",
                    url: "/api/AjaxAPI/AjaxMethod",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    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) {
                        alert(response.responseText);
                   },
                    error: function (response) {
                        alert(response.responseText);
                   }
                });
            });
        });
    </script>
</body>
</html>
 
 

Configuring the JSON Serializer setting

The above program will work but you will see undefined values in the JavaScript Alert Message Box.
What is Web API, why to use it and how to use it in ASP.Net Core
 
In order to resolve it, the JSON serializer settings need to be configured in the Program.cs file.
For more details on configuring JSON serializer settings in ASP.Net Core 7, please refer my article Configuring Newtonsoft library in ASP.Net Core 7.
 
 

Screenshot

What is Web API, why to use it and how to use it in ASP.Net Core
 
 

Downloads