Create jQuery client that invokes the minimal APIs (Sign In and Sign Out)

In the previous part of this multipart article series we migrated the minimal APIs to API controller in order to understand the efforts involved in the process. So far we have learned various aspects of creating minimal APIs. Now let's learn to create client applications that consume the minimal APIs. If you know how to invoke a controller based Web API using client side libraries such as jQuery, you will find this process quite similar. But if you haven't done that before you will find this part interesting. To that end this part teaches you to invoke the minimal APIs using jQuery Ajax.

Before we write any code, let's see how the client UI looks like and how does it work.

See the following figure that shows the client page making requests to the minimal APIs.

As you can seem there are three buttons at the top - Sign In, Sign Out, and Fill Drop Down. The Sign In button retrieves a JWT by supplying a fixed user ID and password. In a more real world client you will have a login dialog or page that captures these details. Upon successful sign in a message is displayed to the user as shown below:

The Sign Out button removes the JWT issued earlier. The Fill Drop Down button loads the initial Employee IDs in the drop down list.

The Employee IDs are displayed in the drop down list below the buttons. Upon selecting an Employee ID, its First Name and Last Name are displayed in the respective textboxes.

The Insert, Update, and Delete buttons are used to initiate the corresponding operations. Since Employee ID is an identity column, you can enter First Name and Last Name and hit the Insert button to add it. The Update modifies the Employee ID selected from the drop down list. Finally, Delete removes the selected Employee ID.

Now that you know how  the client page is going to work, let's get started.

Open the same project that you developed in the preview parts (the one that contains Employees minimal APIs, and Security minimal APIs).

Then place jQuery library in the wwwroot folder as shown below:

Then add a new controller named HomeController in the Controllers folder. Also add Index view in the Views > Home folder.

Open the Index.cshtml view and add a script reference to jQuery library as shown below:

 <script src="~/Scripts/jquery-3.1.1.min.js"></script>

The markup the renders the data entry form is shown below:

<h1>Employee Manager</h1>
<form>
    <button id="signin" type="button">Sign In</button>
    <button id="signout" type="button">Sign Out</button>
    <button id="filldropdown" type="button">Fill Drop Down</button>
    <br /><br />
    <div id="msg"></div>
    <br /><br />
    <table border="1" cellpadding="10">
        <tr>
            <td>Employee ID :</td>
            <td>
                <select id="employeeid"></select>
            </td>
        </tr>
        <tr>
            <td>First Name :</td>
            <td><input id="firstname" type="text" /></td>
        </tr>
        <tr>
            <td>Last Name :</td>
            <td><input id="lastname" type="text" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="insert" value="Insert" />
                <input type="button" id="update" value="Update" />
                <input type="button" id="delete" value="Delete" />
            </td>
        </tr>
    </table>
</form>

The important elements are marked in bold letters. Note their IDs carefully because you will need them in the jQuery code.

Then add a <script> block in the <head> section. The following code shows the skeleton of various event handlers:

$(document).ready(function () {

    $("#signin").click(function () {
    });

    $("#signout").click(function () {
    });

    $("#filldropdown").click(function () {
    });

    $("#employeeid").change(function () {
    });

    $("#insert").click(function () {
    });

    $("#update").click(function () {
    });

    $("#delete").click(function () {
    });
});

As you can see, jQuery ready() wires seven event handlers. We will now write these event callbacks one by one and we will also discuss the relevant code.

The click callback of the signin button is shown below.

$("#signin").click(function () {
    var options = {};
    options.url = "/minimalapi/security/getToken";
    options.type = "POST";
    var obj = {};
    obj.userName = "User1";
    obj.password = "Password1";
    options.data = JSON.stringify(obj);
    options.contentType = "application/json";
    options.dataType = "json";
    options.success = function (token) {
        sessionStorage.setItem("token", token);
        $.ajaxSetup({
            beforeSend : function (request) {
                    request.setRequestHeader("Authorization",
"Bearer " + sessionStorage.getItem("token"));
            }
        });
        $("#msg").html("<h2>Sign In Success</h2>");
    };
    options.error = function () {
        $("#msg").html("<h2>Sign In Error</h2>");
    };
    $.ajax(options);
});

We begin by creating an options object. The url property of the options object points to the getToken endpoint we created in the previous parts of this article series. The HTTP verb used is POST and is specified using the type property.

The obj object wraps the userName and password that we want to use for authentication. In a realistic case this will come from some textbox and password box. We then convert the obj into JSON form using JSON.stringify() method and set the data property of the options object. This data will accompany the Ajax POST request.

The dataType is set to json to indicate that response data is in JSON format. Recollect that the getToken handler method returns a JWT in JSON format.

The success function receives the JWT sent by the getToken minimal API. We store the JWT in the browser's sessionStorage object. This is done using the setItem() method.

At the time of making Ajax calls to the CRUD endpoints, we need to set the Authorization HTTP header with this JWT. Instead of doing that in each and every Ajax call we do it only once with the help of $.ajaxSetup() method of jQuery. The $.ajaxSetup() method is used to configure global Ajax setup of jQuery. We set the beforeSend function inside the $.ajaxSetup(). The beforeSend function sets the Authorization HTTP header using setRequestHeader() method. Notice how the JWT from sessionStorage is appended to "Bearer " while setting the Authorization header.

We then display a success message in the msg <div> element using the html() method.

In case there is any error while calling the getToken API, we display an error message in the msg element using the error callback.

Finally, we initiate the Ajax call using $.ajax() method.

The following figure shows a successful run of the above code:

The click callback of the signout button looks like this:

$("#signout").click(function () {
    sessionStorage.removeItem("token");
    $.ajaxSetup({
            beforeSend : null
    });
    $("#msg").html("<h2>Sign Out Success</h2>");
});

The signout callback removes the JWT stored in the sessionStorage using removeItem() method. Since  the JWT has been removed the global Ajax setup is also reset by removing the beforeSend function. A success message is displayed in the msg element. The following code shows a successful run of this code:

In the next part of this series we will call CRUD APIs from the jQuery code. 

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Kriya and Meditation online course are available here.

Posted On : 10 March 2022


Tags : ASP.NET ASP.NET Core MVC .NET Framework C# Visual Studio