Tutorial – Implementing your own ASP NET Web API from Start [with Code]

Tutorial – Implementing your own ASP NET Web API from Start [with Code]

In this Tutorial I will teach how to Implement your own ASP NET Web API from start. This API will fetch records from the database and provides the consumer with these records in JSON format. This API also implements authentication, meaning users have to provide API Key and Secret for consuming this API.

Create Web API 2 Controller

Add a Web API 2 Controller in your MVC application and name it ‘APIController’.

add web api 2 controller

You will also find that the Visual Studio has added a file WebApiConfig.cs to the ‘App_Start’ folder. This file contains the routes for this Web API.
To force the API to return JSON (and not XML), add the below line at the end of the ‘Register()’ method on ‘WebApiConfig.cs’.

config.Formatters.Remove(config.Formatters.XmlFormatter);

So the ‘WebApiConfig.cs’ file will look like this:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Formatters.Remove(config.Formatters.XmlFormatter);
    }
}

You will also have to add the reference of WebApiConfig in Global.asax. For this go to the ‘Application_Start()’ method of Global.aspx, then add the below line (add it just above the line which registers the routes).

System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);

It should look like:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}
This ASP NET Web API will fetch Products from Database

I have a Products table in my Database that has 77 products. This ASP NET Web API will fetch these products and provide then in JSON format.

The Products table look like this:

products table

I am providing you with the script of the products table which you can run in your SQL Server Management Studio.

Products Table Script

To fetch the records from database I will use Entity Framework. So create an EDMX file of your database in order to use Entity Framework.

If you don’t know how to create EDMX file please read my tutorial – Entity Framework – How to Create an EDMX file.

Creating API Methods in the Controller

I will create 3 API methods in the Controller so I will be actually creating 3 ASP NET Web APIs. These are:

1. GetAllProducts(): It will return all products from the table and does not have authentication procedure.

2. GetProduct(): It will return products in page-by-page manner, with maximum 10 products per page. It has authentication procedure.

3. SearchProduct: It will return products with a matching name. The ‘name’ will be send to the method. It too has authentication procedure.

Create ‘GetAllProducts()’ Method

Add the below code, to add the ‘GetAllProducts()’ method, to the controller.

public IEnumerable<Product> GetAllProducts()
{
    using (var context = new Entities())
    {
        var record = context.Products.Select(x => x).ToArray();
        return record;
    }
}

This method has a return type of IEnumerable, I am fetching all products from Entity Framework Query and filling then on the ‘record’ variable. This variable is returned at the end.

Call ‘GetAllProducts()’ on the browser
Run your application then navigate to http://localhost:60174/api/API. You will see all the Products in json format.

Calling GetAllProducts method on browser returns json

Note – In the URL ‘60174’ is my application port given by VS, your post may be different and you have to change it with you port.

Call ‘GetAllProducts()’

Create ‘GetProduct()’ Method

In your controller add another method named GetProduct(). Its code is given below:

public IHttpActionResult GetProduct(int id)
{
    using (var context = new Entities())
    {
        var totalRecords = context.Products.Count();
        var pageSize = 10;
        var skip = pageSize * (id - 1);
        var canPage = skip < totalRecords;

        IEnumerable<Product> record = null;
        if (canPage)
        {
            record = context.Products
                     .OrderBy(x => x.ProductID)
                     .Skip(skip)
                     .Take(pageSize)
                     .ToArray();
        }
        var output = new { Total = totalRecords, CurrentPage = id, PageSize = pageSize, Product = record };
        return Ok(output);
    }
}
  • This method will return Product records in page-by-page manner. For this it accepts the page number in its parameter (int id) and then fetches the records of that page and returns them in JSON response.
  • It also sends total records, current page & page size in the json.
  • Number of records per page is 10.
I have taken the return type as IHttpActionResult this allows me to also return HttpStatusCode along with the response json. Here I have returned HttpStatusCode as ‘Ok’.

Call ‘GetProduct()’ on the browser
To Call the ‘GetProduct()’ method on your browser navigate to the URL – http://localhost:60174/api/API/2

You will see the JSON returned by it.

GetProduct() json

Notice I passed ‘2’ to the URL which is the 2nd page number. The JSON also contains – “Total”:77,”CurrentPage”:2,”PageSize”:10 and so also provides total records, current page and page size.

Securing ‘GetProduct()’Method
I will now secure this method so that only those request containing API Key and Secret should get the JSON. For request containing invalid key or secret will get Forbidden Response (403) response.

For create this feature add a function ‘Authenticate()’ to the controller:

bool Authenticate()
{
    var APICrendential = new[] { new { Key = "Key1", Secret = "Secret1" }, new { Key = "Key2", Secret = "Secret2" }, new { Key = "Key3", Secret = "Secret3" } };

    System.Net.Http.Headers.HttpRequestHeaders headers = Request.Headers;
    string key = "", secret = "";
    if (headers.Contains("Key"))
        key = headers.GetValues("Key").First();
    if (headers.Contains("Secret"))
        secret = headers.GetValues("Secret").First();

    int count = (from t in APICrendential where t.Key == key && t.Secret == secret select t).Count();
    return count == 0 ? false : true;
}

This method checks the Request Header to find Key & Secret. They are matched with those contained in the variable ‘APICrendential’. If they matches the function returns true else false.

Here I am matching the API Key and Secret with 3 values which are:

  • 1. Key – ‘Key1’ & Secret – ‘Secret1’
  • 2. Key – ‘Key2’ & Secret – ‘Secret2’
  • 3. Key – ‘Key3’ & Secret – ‘Secret3’

In real world you will match them against the database.

Now call the ‘Authenticate()’ function on the first line of the GetProduct() method and return 403 error (Forbidden) for unauthenticated requests.

public IHttpActionResult GetProduct(int id)
{
    if (!Authenticate())
        return ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden));
    using (var context = new Entities())
    {
        ... 
    }
}

Now run the same URL in your browser. This time you will get ‘HTTP ERROR 403’ because you haven’t provided the API Key and Secret.

http error 403

I will tell you how to provide the Key and Secret on the Header of the API request when I will consume this API.

Call ‘GetProduct()’

Create ‘SearchProduct()’ Method

Unlike the above 2 method that were HTTP GET types I will create this method as HTTP POST. So this method will only be consumed by requests of type HTTP POST.

[HttpPost]
public IHttpActionResult SearchProduct(string pageNo)
{
    if (!Authenticate())
        return ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden));

    using (var context = new Entities())
    {
        var record = context.Products.Where(x => x.ProductName == pageNo).ToArray();
        var output = new { Product = record };
        return Ok(output);
    }
}

To make this a POST API, just apply the [HttpPost] attribute to the method.

DOWNLOAD

Note – you won’t be able to call this method on the browser as this is a POST type.

I will tell you how to call this method during the consuming procedure.

Consuming these ASP NET Web APIs in MVC and jQuery

Now it’s time to consume these 3 APIs. I have written 2 tutorials for it.

1. First that does it in MVC – Consuming ASP NET Web API

2. Second that does it in jQuery – Consuming ASP NET Web API in jQuery

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.