Web
Analytics
WebApi Example With Cross Origin Support - Tutorial

For Consultation : +91 9887575540

Stay Connected :

Step1 : Create New Project

Go to File > New > Project > Select asp.net web application > Entry Application Name > Click OK >Select Empty Template > Check Web API CheckBox > > OK

Some Snap Shots of above procedure are given below.

1_WebApi WebApi_New_Project

 

Step2 : Add Database Table (Here Database Name : Exercice and Table- Customer).

Table Snap Shot is given below

DatabaseTable

Step3:Add ADO.NET Entity Model along with Entity Framework 6.0 Installation

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Snap Shots of above procedure is given below

3_Create_New_Ado.NET_Entity_Model 5_Database_Selection 6_Entity 7_Table

Above procedure will automatically install entity framework 6.0 after it.

Step 4:Enable Cors

Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP.

Lets see that how we can enable cors

9_Add_Cors

So Now our Model is ready and cors are enabled.

Step5: Create new Empty WebAPI Controller and write following code (A simple method which is returning a simple HTTPResponse message)

10_Web_Api_Controller

In Home WebAPI Controller

Run an see output(URL: http://localhost:49885/api/Home)

11_Web_API_Output

Now our web api is ready to access cross domains.

Now we will create a website which will use this newly created webapi.

Note: Keep WebAPI running at localhost and do not close webapi project in visual studio.

Step 5: Now We are going to create web client application.

Go to File > New > Project > Select asp.net web application > Enter Application Name > Click OK >Select MVC Template > OK

 

Step 6: Write new Action in Home Controller

public ActionResult UseWebApi()

{

return View();

}

Add View for this Action and write following code

12_OutputOutput

Download Source Code

 

Select your currency