In this article I will explain a simple tutorial with an example, how to create Web API in Visual Studio 2022 step by step in ASP.Net Core (.Net Core 3) MVC.
Note: For beginners in ASP.Net Core (.Net Core 3) MVC, please refer my article ASP.Net Core 3: 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 Startu.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
.Net Core 3: Create Web API in Visual Studio 2022 step by step
 
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)
{
    services.AddMvc()
     .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
     services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
 
 

Model

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

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 and click on Add and then Add New Item.
Now from the Add New Item window, choose the API Controller – Empty option as shown below.
Then give it a suitable name and click on Add Button.
.Net Core 3: Create Web API in Visual Studio 2022 step by step
 
 

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 class and updates the DateTime property with the Current Date and Time and returns the PersonModel class object.

Attributes

Route: The Route attribute defines its Route for calling the Web API method.
HttpPost: The HttpPost attribute which signifies that the method will accept 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.
 
[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, simple the View is returned.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
 
 

View

HTML Markup

The View consists of an HTML INPUT TextBox and a Button. The Button has been assigned with a jQuery click event handler.
When the Button is clicked a jQuery AJAX call is made to the Web API Controller’s Action 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 with the Web API Controller’s Action method name.
The value of the AntiForgery Token is read from the Hidden Field and passed as Request Header in the jQuery AJAX call.
Finally, inside the success event handler of 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>
 
<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>
 
 

Screenshot

.Net Core 3: Create Web API in Visual Studio 2022 step by step
 
 

Downloads