ASP.NET WEB API Basics

Originally Posted By myself on 2/21/2016 at http://rchannel.azurewebsites.net/ChannelR/Details/20

SUPERCHARGE YOUR PROGRAMMING SKILLS WITH WEB SERVICES, JQUERY AJAX, ASP.NET WEB API CREATION / CONSUMPTION, …

PREREQUISITES

  • Fresh knowledge of intermediate level ASP.NET MVC programming.
  • Visual studio Ultimate or Express for Web 2010–2015.
  • Google Chrome.

A. WHAT IS ASP.NET WEB API ?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. (www.asp.net/web-api)

WHAT ARE WEB SERVICES ?

“A web service returns data that’s intended to be used by another program, rather than displayed directly to the user; another common term for this is API, i.e. Application Programming Interface. Rather than returning HTML, it returns data that’s structured to be easy for computers to extract the values. Common formats are XML and JSON.

Both web services and normal web pages use HTTP as the data transfer protocol. The difference is in how they’re used by clients.” (http://stackoverflow.com/questions/21950255/what-is-the-different-between-http-request-and-web-service)

Examples of HTTP Methods used for Web Services:

GET

Used to obtain data off a server. For example, whenever you open any webpage on the web browser; you are making a GET request to the server hosting that webpage to obtain information which is normally formated in html to make it look nice.

POST

Used to upload data to a server. For example, whenever you upload your content on a social media website you are requesting a POST request to the server hosting that content.

PUT

Used to modify existing content from a server. For example, whenever you modify the information you have uploaded on a social media website; your requesting a PUT request to the server hosting that content.

DELETE

By now you might have guessed, that the DELETE request will simply delete content from a server hosting the content. Well done; your right. :)

CREATING AN ASP.NET WEB API APPLICATION

1. Click File > New > Project > WEB > ASP.NET Web Application > OK

2. Click Web API > OK

MODIFYING THE ASP.NET WEB API APPLICATION

1. Click Solution Explorer > Controllers > ValuesController.cs

2. Replace this:

public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

With this:

public IEnumerable<string> Get()
{
return new string[] { "Tom", "Jim" };
}

3. Execute the application: F5

4. Navigate to the YourLocalHostPathHere/api/values

To avoid conflicts between API controller actions and MVC controller actions, the API actions are routed in the following format: apiName/{controllerName}/{id} by default. Feel free to try the following link for more information about ASP.NET API routing:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Result: As shown below an error message is displayed indicating that the Authorization security option of our template is enable and is preventing our GET request to the localhost server.

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>

5. Delete the [Authorize] attribute from ValuesController.cs to disable Authorize security option in this file.

6. Execute the application again and navigate to the YourLocalHostPathHere/api/values

Result: Below is the XML representation of the information stored in an array in the application. Notice that, by default Google Chrome displays such data in the XML format. 
This is the kind of data that gets formatted in HTML on websites.

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>Tom</string>
<string>Jim</string>
</ArrayOfstring>

CONSUMING THE ASP.NET WEB API IN A RAZOR VIEW

1. Click Solution Explorer

2. Expand Views > Home

3. Double click Index.cshtml

4. Delete everything in Index.cshtml

5. Type the following in Index.cshtml

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<button type="submit" value="Submit" id="BtnGetCustomer">Submit</button>
<script>
$(document).ready
(
function () {
jQuery.support, cors = true;
$('#BtnGetCustomer').click
(
function () {
$.ajax
({
url: '/api/values',
type: 'GET',
datatype: 'xml',
success: function (data) {
alert(data);
$(body).append(data);
}
})
}
)
        }
)
</script>

6. Execute the application; shortcut: F5

7. Click the Submit button

Result: The values stored in an array in the ValuesController were retrieved into the razor view using jQuery and Ajax codes.

Quick note: Feel free to view section F to get an explanation of the jQuery and Ajax syntax used in this section E.

MODIFYING THE ASP.NET WEB API APPLICATION

1. Click Solution Explorer > Controllers > ValuesController.cs

2. Replace this:

public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

With this:

public IEnumerable<string> Get()
{
return new string[] { "Tom", "Jim" };
}

3. Execute the application: F5

4. Navigate to the YourLocalHostPathHere/api/values

To avoid conflicts between API controller actions and MVC controller actions, the API actions are routed in the following format: apiName/{controllerName}/{id} by default. Feel free to try the following link for more information about ASP.NET API routing:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Result: As shown below an error message is displayed indicating that the Authorization security option of our template is enable and is preventing our GET request to the localhost server.

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>

5. Delete the [Authorize] attribute from ValuesController.cs to disable Authorize security option in this file.

6. Execute the application again and navigate to the YourLocalHostPathHere/api/values

Result: Below is the XML representation of the information stored in an array in the application. Notice that, by default Google Chrome displays such data in the XML format. 
This is the kind of data that gets formatted in HTML on websites.

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>Tom</string>
<string>Jim</string>
</ArrayOfstring>

E. CONSUMING THE ASP.NET WEB API IN A RAZOR VIEW

1. Click Solution Explorer

2. Expand Views > Home

3. Double click Index.cshtml

4. Delete everything in Index.cshtml

5. Type the following in Index.cshtml

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<button type="submit" value="Submit" id="BtnGetCustomer">Submit</button>
<script>
$(document).ready
(
function () {
jQuery.support, cors = true;
$('#BtnGetCustomer').click
(
function () {
$.ajax
({
url: '/api/values',
type: 'GET',
datatype: 'xml',
success: function (data) {
alert(data);
$(body).append(data);
}
})
}
)
        }
)
</script>

6. Execute the application; shortcut: F5

7. Click the Submit button

Result: The values stored in an array in the ValuesController were retrieved into the razor view using jQuery and Ajax codes.

Quick note: Feel free to view section F to get an explanation of the jQuery and Ajax syntax used in this section E.

F. EXPLANATION OF SYNTAX USED IN SECTION E

HTML syntax explanation

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<button type="submit" value="Submit" id="BtnGetCustomer">Submit</button>

In line 1: We are referencing the jQuery library to our project in order to access all features of jQuery in our software application.

In line 3: We created a button using intermediate level html syntax and assigned the id “BtnGetCustomer” to it in order to access that button in our jQuery code.
 
jQuery syntax explanation

<script>
$(document).ready
(
function () {
jQuery.support, cors = true;
$('#BtnGetCustomer').click
(
function () {
$.ajax
({
url: '/api/values',
type: 'GET',
datatype: 'xml',
success: function (data) {
alert(data);
}
})
}
)
        }
)
</script>

In line 1: We are telling the system that we are going to type javascript/jQuery codes between the <script> ... </script> tags

In line 2: We are telling the system to only start reading and executing jQuery codes once the html document and all its elements have fully loaded.

In line 3: All the code to be read once the document and all its element have fully loaded are enclosed between parenthesis ... )

In line 4: We are defining a c# method translated into a JavaScript/jQuery function without access specifiers.

In line 5: We are removing specific jQuery features when these are not needed to improve page startup speed using the jQuery.support keywords.

We enabled Cross domain requests to access data access data from our ValuesController. Click on the following link for more information about CORS: http://www.html5rocks.com/en/tutorials/cors/
 
In line 6: We are creating a button click event for our previously created button using its id as a reference to it.

In line 7: We are ensuring that all the code enclosed between our new parenthesis ... )gets executed only once the submit button is click.

In line 8: We are defining a JavaScript/jQuery function as we did in line 4.

In line 9: We are using an AJAX method from the jQuery library to perform an asynchronous http requests; that is to perform HTTP requests like GET,POST,PUT and Delete, without waiting for other requests to be completed.

What is asynchronous?

"As an example; a telephone conversation is asynchronous because both parties can talk whenever they like. If the communication were synchronous, each party would be required to wait a specified interval before speaking." (webopedia.com)

In line 10: We are enclosing the parameters between ({}) of the ajax method as required by the JavaScript/jQuery language. ({...})

Parenthesis () in JavaScript are used for function calls, to surround conditional statements, or for grouping to enforce Order of Operations.

Braces {} are used during the declaration of Object Literals, or to enclose blocks of code (function definitions, conditional blocks, loops, etc).

(http://stackoverflow.com/ , http://stackoverflow.com/questions/9699064/what-do-curly-braces-in-javascript-mean , http://stackoverflow.com/questions/23225375/when-to-use-parentheses-brackets-and-curly-braces-in-javascript-and-jquery)

What is an Object Literal?

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Object_literals)

In line 11: We are adding a string containing the URL to which the request is sent, as a parameter to the ajax function.

In line 12: We are specifying that we want to initiate a GET request from the URL specified in line 11. (Overall from the localhost server since we are hosting our application on that server for testing purposes.)

In line 13: We are specifying that we need the serialized data from the Array in the ValuesController, to be retrieved and converted into the XML format to access it in a Web Browser like Google Chrome.

In line 14: We are specifying the function to be executed in case the GET request successfully outputed the data. The data outputed is stored in the data parameter of the function.

In line 15: We are displaying the data outputed in an Alert Box.