Calling ASP.NET Web API using jQuery

 1. Call ASP.NET Web API from jQuery

Following code shows calling Web API through jQuery. We are calling web API to get list of employee on click on "Get All Employees" button click and append it in ul.

<body>
    <div>
        <input id="btnGetEmployee" type="button" value="Get All Employees" />
        <input id="btnClear" type="button" value="Clear" />
        <ul id="ulEmployees" />
    </div>
</body>
</html>

<script type="text/javascript">
        $(document).ready(function () {
            var ulEmployees = $('#ulEmployees');
            $('#btnGetEmployee').click(function () {
                $.ajax({
                    type: 'GET',
                    url: "api/employees/",
                    dataType: 'json',
                    success: function (data) {
                        ulEmployees.empty();
                        $.each(data, function (index, val) {
                            var fullName = val.FirstName + ' ' + val.LastName;
                            ulEmployees.append('<li>' + fullName + '</li>');
                        });
                    }
                });
            });
            $('#btnClear').click(function () {
                ulEmployees.empty();
            });
        });
 </script>


 2. Calling ASP NET Web API service in a cross domain using jQuery ajax


Browsers allow a web page to make AJAX requests only with in the same domain. Browser security prevents a web page from making AJAX requests to another domain. This is called same origin policy.

There are 2 ways to get around this problem
  • Using JSONP (JSON with Padding) 
  • Enabling CORS (Cross Origin Resource Sharing)


i. Using JSONP (JSON with Padding)

Browsers allow to consume JavaScript that is present in a different domain but not data. with JSONP, JSON data is wrapped in JavaScript function. Since the data is wrapped in a JavaScript function, this can be consumed by a web page that is present in a different domain.

Steps to make ASP.NET Web API Service to return JSONP formatted data and consume it from a cross domain ajax request,
Step 1 : To support JSONP format, installs WebApiContrib.Formatting.Jsonp package.
Install-Package WebApiContrib.Formatting.Jsonp

Step 2 : Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder

var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
config.Formatters.Insert(0, jsonpFormatter);

Step 3 : In the ClientApplication, set the dataType option of the jQuery ajax function to jsonp 
dataType: 'jsonp'



ii. Enabling CORS (Cross Origin Resource Sharing)

Step 1 : Install Microsoft.AspNet.WebApi.Cors package. 
Install-Package Microsoft.AspNet.WebApi.Cors

Step 2 : Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder,
EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");
config.EnableCors();

Step 3 : In the ClientApplication, set the dataType option of the jQuery ajax function to json
dataType: 'json'

EnableCors attribute can be applied on a specific controller or controller method. 
Example:- 
[EnableCorsAttribute("*""*""*")]
public class EmployeesController : ApiController
{
}

To disable CORS for a specific action apply [DisableCors] on that specific action

When CORS is enabled, the browser sets the origin header of the request to the domain of the site making the request. The server sets Access-Control-Allow-Origin header in the response to either * or the origin that made the request. * indicates any site is allowed to make the request.



Comments