In this article I will explain with an example, how to call (consume) Web API 2 using JavaScript XmlHttpRequest (XHR) and AJAX in ASP.Net Core MVC.
This article will explain how to make a POST call to Web API 2 Controller’s method using JavaScript XmlHttpRequest (XHR) and AJAX in ASP.Net Core MVC.
Note: For beginners in ASP.Net MVC Core, 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.
 
 
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; }
}
 
 
Web API Controller
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the API Controller – Empty option as shown below.
ASP.Net Core: Call (Consume) Web API using JavaScript XmlHttpRequest (XHR) and AJAX
 
Then give it a suitable name and click Add.
Action Method
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.
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 Http Post requests.
[Route("api/[controller]")]
[ApiController]
public class AjaxAPIController : ControllerBase
{
    [Route("AjaxMethod")]
    [HttpPost]
    public PersonModel AjaxMethod(PersonModel person)
    {
        person.DateTime = DateTime.Now.ToString();
        return person;
    }
}
 
 
Controller
Now you will need to add one empty Controller along with a View. The View will be used for calling the Web API 2 Controller’s method using JavaScript XmlHttpRequest (XHR) and 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();
    }
}
 
 
View
The View consists of an HTML TextBox element and a Button. The Button has been assigned a JavaScript OnClick event handler and when the Button is clicked, the CallWebAPI JavaScript function gets called.
Inside the CallWebAPI JavaScript function, first the TextBox is referenced using JavaScript and its value is fetched.
The fetched value is set into a JavaScript object (person) after wrapping it in JSON format.
The URL for the JavaScript XmlHttpRequest (XHR) call is set to the Web API 2 Controller’s method i.e. /api/AjaxAPI/AjaxMethod.
The person object is sent to the Web API as parameter and the returned response is displayed using JavaScript Alert Message Box after converting it to a JSON object.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <input type="text" id="txtName"/>
    <input type="button" id="btnGet" value="Get Current Time" onclick="CallWebAPI()"/>
    <script type="text/javascript">
        function CallWebAPI() {
            var name = document.getElementById("txtName").value;
            var person = '{Name: "' + name + '" }';
            var request;
            if (window.XMLHttpRequest) {
                //New browsers.
                request = new XMLHttpRequest();
            }
            elseif (window.ActiveXObject) {
                //Old IE Browsers.
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (request != null) {
                var url = "/api/AjaxAPI/AjaxMethod";
                request.open("POST", url, false);
                request.setRequestHeader("Content-Type", "application/json");
                request.onreadystatechange = function () {
                    if (request.readyState == 4 && request.status == 200) {
                        var response = JSON.parse(request.responseText);
                        alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
                    }
                };
                request.send(person);
            }
        }
    </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.
ASP.Net Core: Call (Consume) Web API using JavaScript XmlHttpRequest (XHR) and AJAX
 
In order to resolve it, the JSON Serializer settings need to be configured in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
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 use Newtonsoft library for JSON serialization.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
 
Note: For more details, please refer my article [SOLVED] LowerCase JSON Property Names in ASP.Net Core.
 
 
Screenshot
ASP.Net Core: Call (Consume) Web API using JavaScript XmlHttpRequest (XHR) and AJAX
 
 
Downloads