Monday, 31 December 2018

How to call an ASP.NET Web API service in a cross domain using jQuery ajax?

Browsers does not allow cross domain ajax requests. There are 2 ways to get around this problem

1.     Using JSONP (JSON with Padding) 
2.     Enabling CORS (Cross Origin Resource Sharing)

Using JSONP: 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, execute the following command using NuGet Package Manager Console which 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 = newJsonpMediaTypeFormatter(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'

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/jquery-1.10.2.js"></script>
    
    <script type="text/javascript">
        $(document).ready(function () {
            var ulEmployees = $('#ulEmployees');
            $('#btn').click(function () {
                $.ajax({
                    type: 'GET',
                    url: "api/employees/",
                    dataType: 'jsonp',
                    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>

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

Enabling CORS: To allow cross domain ajax calls by enabling CORS

Step 1 : 
Install Microsoft.AspNet.WebApi.Cors package. Execute the following command using NuGet Package Manager Console. Make sure to select "EmployeeService" project from "Default project" dropdown.

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'

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Scripts/jquery-1.10.2.js"></script>
    
    <script type="text/javascript">
        $(document).ready(function () {
            var ulEmployees = $('#ulEmployees');
            $('#btn').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>

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

EnableCors attribute can be applied on a specific controller or controller method. 

If applied at a controller level then it is applicable for all methods in the controller. To apply it at the controller level

1. There is no need to create an instance of 
EnableCorsAttribute in Register() method of WebApiConfig.cs file. Call the EnableCors() method without any parameter values.

config.EnableCors();


2. Apply the  EnableCorsAttribute on the controller class
[EnableCorsAttribute("*""*""*")]
public class EmployeesController : ApiController
{
}


In the same manner, you can also apply it at a method level if you wish to do so.


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-Originheader in the response to either * or the origin that made the request. * indicates any site is allowed to make the request. 

No comments:

Post a Comment