In order to call ASP.Net Web API
service, add an HTML page in your project. Add reference of JQuery. Your HTML
page should look like below.
Two input buttons, one to get list of employees and one to
clear the list. An unordered list to show the list of employees.
In the document ready event, write button click events as
follows:
Here
in this example, both the client and the Web API service are in the same
project. So we can use the relative or full path for the controller in ajax
call. But if client is in separate project and Web API service is in another
project, then it is difficult to call the controller directly using relative or
full path.
Calling ASP.Net Web API service in a cross domain using
JQuery ajax:
Browsers
allow web page to make ajax request only within the same domain. Browser’s
security prevents making ajax calls to different domains. This is called same
origin policy.
Below
urls have same origin.
http://localhost:123/api/Employee
http://localhost:123/Employees.html
.
Different origin, because port numbers are different:
http://localhost:123/api/Employees
http://localhost:456/Employees.html
Different origin, because protocols are different:
http://localhost:123/api/Employees
https://localhost:456/Employees.html
Different origin, because domains are different:
http://abc.com
http://abc.net.
For security reasons, browsers do not allow cross domain
ajax request. There are two ways to get around with this.
·
JSONP (JSON with Padding)
·
CORS (Cros Origin Resource Sharing)
What is JSONP?
JSONP stands for JSON with Padding. All JSONP does is wraps
a data in a function.
In
order to allow JSONP to work, we need to install nuget Webcontrib.Formatting.JsonP. Add
below lines of code in WebApiConfig file in Register method
CORS (Cross Origin Resource Sharing):
To
enable CORS, we need to install nugget Microsoft.AspNet.WebAPI.Cors
package. Add below lines of code in
WebApiConfig file in Register method