Web API- ASP.NET Web API Tutorials - Part 01

ASP.NET Web API

ASP.NET Web API Tutorials - Part 01

What is web api

Asp.net web API is a platform to create Restful Services which is based on HTTP Request. Web API can be reached to the multiple clients like web based, mobile based etc. Web API Request and Response can be in XML and JSON.
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. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
When you're building APIs on the Web, there are several ways you can build APIs on the Web. These include HTTP/RPC, and what this means is using HTTP in Remote Procedure Call to call into things, like Methods, across the Web.
The verbs themselves are included in the APIs, like Get Customers, Insert Invoice, Delete Customer, and that each of these endpoints end up being a separate URI.

We have Following HTTP Request which we can use in Web API:-
Get: - To Fetch the data(Read)
Post: - To submit the data(Create)
Put: -To Update the data(Update)
Delete: - To Delete the data(Delete)

Step 1 – Create new project

Open Microsoft Visual Studio and create a new project (File -> New -> Project). Select “Installed” Templates, select Visual C#. then select Web. In the list of available templates, select ASP.NET Web Application (.NET Framework). Give a name for your project, for my demo, I put “webapi”, click OK.
Visual Studio - New Project
ASP.NET Web Application
In the next modal dialog, you may choose any suitable template. Let’s select Web API, so it will prepare all basic initial files for the project. Click OK.
ASP.NET Web API
Done. Now you can browse the generated folders and files in the Solution Explorer. There are application configs, help page data, few controllers, fonts, css and js files.
ASP.NET Web API Created

Routing Table

By default, the server uses the Routing Table located in App_Start/WebApiConfig.cs.
Default WebApiConfig.cs
Pay attention to routeTemplate: "api/{controller}/{id}", it explains the api routing.
Now, let’s make a basic example. In this tutorial we will prepare API for Users, which is pretty general entity/object of every system.

Adding a User model

The model represents the user, we will include various fields like id, name, email, phone and role.
In Solution Explorer, right-click in the Models folder, select Add then select Class. Then provide class name: User. The model class is ready.
Add new Class
Add new Class - User
Now we just add all the fields we decided to add:
1public class User
2{
3    public int id { get; set; }
4    public string name { get; set; }
5    public string email { get; set; }
6    public string phone { get; set; }
7    public int role { get; set; }
8}

Add a User controller

In Web API, the controller is an object that handles all HTTP requests. In Solution Explorer, right-click the Controllers. Select Add, then select Controller.
Add new Controller
Web API 2 Controller with read/write actions
In the given dialog, select Web API 2 Controller with read/write actions. Name the controller – UsersController. It will prepare the controller with all CRUD actions.
Users Controller
In this article I prepared a basic example with dummy list of users:
01public class UsersController : ApiController
02{
03    private User[] users = new User[]
04    {
05        new User { id = 1, name = "Haleemah Redfern", email = "email1@mail.com", phone = "01111111", role = 1},
06        new User { id = 2, name = "Aya Bostock", email = "email2@mail.com", phone = "01111111", role = 1},
07        new User { id = 3, name = "Sohail Perez", email = "email3@mail.com", phone = "01111111", role = 1},
08        new User { id = 4, name = "Merryn Peck", email = "email4@mail.com", phone = "01111111", role = 2},
09        new User { id = 5, name = "Cairon Reynolds", email = "email5@mail.com", phone = "01111111", role = 3}
10    };
11    // GET: api/Users
12    [ResponseType(typeof(IEnumerable<User>))]
13    public IEnumerable<User> Get()
14    {
15        return users;
16    }
17    // GET: api/Users/5
18    public IHttpActionResult Get(int id)
19    {
20        var product = users.FirstOrDefault((p) => p.id == id);
21        if (product == null)
22        {
23            return NotFound();
24        }
25        return Ok(product);
26    }
27    ...

Step 2 – Deployment

Now you can build your solution (Ctrl+Shift+B in Visual Studio), once the build is succeeded, you can run it. Click F5 and it will open in your browser automatically at your localhost in an available port (e.g. http://localhost:61024/). Most probably, you don’t want to keep it running in the Visual Studio all the time, and you prefer to keep it as service).
In this case, we can deploy it to a local dedicated server using IIS (Internet Information Services). It is pretty easy.
Firstly, open the IIS, on the left side under Sites – add a New Website (from the right panel or right-click on the Sites). Put the details: Site name “webapi.localhost.net”, Physical path “C:\projects\webapi” (where your solution is located), Binding – http or https, Host name is same – “webapi.localhost.net”. Click OK.
IIS - Add Website
IIS should run the Web API service on webapi.localhost.net.
Now if you try to open webapi.localhost.net in your browser, it won’t open the result we created. It happens because browser tries to resolve this address webapi.localhost.net as global domain. In order to map this domain name with local server we need to modify the local hosts file. On Windows (v10) the hosts file exists at C:\Windows\system32\drivers\etc folder. The file doesn’t have own extension, it is “hosts” file.
Copy it to another location and open it in editor
C:\Windows\system32\drivers\etc\hosts file
You need to add the following in the end of this file:
1# Web API host
2127.0.0.1       webapi.localhost.net
Now you need to put the modified file back to C:\Windows\system32\drivers\etc folder. As this folder is protected by windows by default, you will get access denied warning message. So you need to copy the file “As Administrator”.
After the file is updated, the webapi.localhost.net should load from your localhost (C:\projects\webapi).

Testing API

It is time to test the API methods we created for our Web server: api/users and api/users/{id}. Open “http://webapi.localhost.net/api/users” in your browser. You should get the following output:
api/users result
As we are creating the external API which should be accessible outside, we need to test our API from another page. The easiest way is to use a development toolbar (which exists in any modern browser). Usually it is activated when you press F12. Go to ‘Console’ tab. Below I prepared two small examples which you can use to test the APIs
In case if jQuery is available, you can use:
1$.ajax({
2    type: "GET",
4    success: (data) => {
5        console.log(data);
6    }
7});
Otherwise, using native javascript, you can use:
1var xhr = new XMLHttpRequest();
3xhr.onload = function() {
4    console.log(xhr.response);
5};
6xhr.send();
Very likely you will receive the following error
Access-Control-Allow-Origin error
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
The reason is that regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they’re limited by the same origin policy. Extensions aren’t so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.

Adjust Cross-Origin Resource Sharing (CORS)

In order to solve this, we need to enable the CORS in our solution. In Visual Studio open Package Manage Console (available in bottom, between of Error List and Output). Run the following:
Install-Package Microsoft.AspNet.WebApi.Cors
It will install the WebApi.Cors reference. Then open “App_Start\WebApiConfig.cs” file. Add config.EnableCors(); before config.MapHttpAttributeRoutes();
Enable WebApi.Cors
Then go back to our UsersController.cs and add [EnableCors(origins: "*", headers: "*", methods: "*")] before the class definition
Enable Cors in Controller
Finally – rebuild the project again. Then try to test the APIs again, now it should work
Successful Web API request

How to Access Web API using Ajax


How to Access Web API using Ajax

Now move to the home controller and add View. Now use the following JQuery code to retrieve this web api
  
  
  <header>
   
    <script src="~/Scripts/jquery-1.7.1.min.js"></script> 
    <script>
        $(document).ready(
            function () {
                $(window).load(function ()
                {
                    $.ajax(
                      {
                          url: "/api/Values",
                          type: "Get", success:
                              function (data)
                              {
                               for (var i = 0; i < data.length; i++)
                                  {
                                      var opt = new Option(data[i]);
                                      $('#op1').append(opt);
                                  }
                              }
                      });
                });
            }); </script> 
</header>

    <select id="op1"></select>

Comments

AB InfoTech

reach out : abinfotechnology@gmail.com