Introduction - ASP.NET Web API 2: Beginner Guide (2015)

ASP.NET Web API 2: Beginner Guide (2015)

Introduction

ASP.NET Web API is a framework for building HTTP services that can be accessed from various clients, such as browsers and mobile devices. ASP.NET Web API was introduced as part of ASP.NET MVC 4; however, it has its origins in WCF as WCF Web API. This new HTTP service model is simple to develop and contains common HTTP features, including Caching, Status Code, and so on.

In this short book, we will discuss Web API design, concepts, features, and compare Web API with WCF.

About this book

This short Book explains Web API design, concepts, features, and help page generation. This is a starter guide for those who want to quickly understand the basics of Web API. Topics covered in this book are:

· Implementing Web API

· Web API Client Implementations – ASP.NET MVC and jQuery

· Scaffolding with Web API – Entity Framework

· Routing in Web API

· Implementing Multiple Serialization Options

· Help Page Generation

Share your feedbacks, criticisms, and suggestions of improvements to author.ambily@outlook.com

Implementing a Web API Project

Let’s start our discussion with a sample Web API project. We will be using Visual Studio 2013 as our development environment. Our first step will be to create an ASP.NET MVC project based on the Web API template, as shown in Figure 1.

image

Figure 1: Creating an ASP.NET MVC project based on the Web API template

Next, we’ll create a sample model inside the model folder in the MVC solution. Right click on the Model folder from the solution explorer and select Add -> Class as shown in Figure 2.

image

Figure 2: Add new Model

For this walk-through, I am using the Product model defined in Listing 1.

Listing 1: Defining the Product model

public class Product

{

public int Id { get; set; }

public string Name { get; set; }

public string Category { get; set; }

public decimal Price { get; set; }

}

Once the product model is ready, let us create a new API controller inside the controllers’ folder to process the Product model. By default, an MVC project based on the Web API template adds two controllers: one inherited from the Controller class and the other from ApiController class.

Right-click the controllers folder in Solution Explorer and add a new controller by selecting the Empty API controller option under template as shown in Figure 3.

image

Figure 3: Add Empty API Controller

Provide appropriate name for the new controller; say ProductsController.

image

Figure 4: Add Controller

ProductsController will define two methods for getting list of products and selected product based on product id. The code for the sample controller should look like that shown in Listing 2.

Listing 2: Adding an ApiController class to the sample project

public class ProductsController : ApiController

{

//Define the products list

List<Product> products = new List<Product>();

/// <summary>

///Web API method to return list of products

/// </summary>

/// <returns></returns>

public IEnumerable<Product> GetAllProducts()

{

GetProducts();

return products;

}

private void GetProducts()

{

products.Add(new Product { Id = 1, Name = "Television", Category = "Electronic", Price = 82000 });

products.Add(new Product { Id = 2, Name = "Refrigerator", Category = "Electronic", Price = 23000 });

products.Add(new Product { Id = 3, Name = "Mobiles", Category = "Electronic", Price = 20000 });

products.Add(new Product { Id = 4, Name = "Laptops", Category = "Electronic", Price = 45000 });

products.Add(new Product { Id = 5, Name = "iPads", Category = "Electronic", Price = 67000 });

products.Add(new Product { Id = 6, Name = "Toys", Category = "Gift Items", Price = 15000 });

}

/// <summary>

/// Web API method to retrurn selected product based on the passed id

/// </summary>

/// <param name="selectedId"></param>

/// <returns></returns>

public IEnumerable<Product> GetProducts(int selectedId)

{

if (products.Count() > 0)

{

return products.Where(p => p.Id == selectedId);

}

else

{

GetProducts();

return products.Where(p => p.Id == selectedId);

}

}

}

Run the project and access the API by appending the uniform resource locator (URL) with /api/Products, as in http://localhost: 59509/api/Products. This api call will return the list of Products. We can also access the GetProducts method by passing the SelectedId argument as part of the query string:http://localhost:59509/api/Products?SelectedId=2.

By default Web API returns JSON data, so when you run the Web API directly from browser, it will prompt to save or open the JSON output. Following Figure shows the api output for the /api/Products request.

image

Figure 5: Web API Response - JSON format

Passing Complex Objects to a Web API Method

Passing a simple value is a straightforward process in Web API, but in most cases you’ll need to pass a complex object as a method parameter. You can pass these objects either by using the [FromUrl] or by using [FromBody] attribute. The [FromBody] attribute reads data from the request body. However, the attribute can be used only once in the method parameter list.

Let us understand the importance of using complex parameters using the code snippet in Listing 3, which expects a complex object, Time, as its input.

Listing 3: Passing a complex object as a method parameter

public class SampleController : ApiController

{

/// <summary>

/// Get the time based on passed parameters

/// </summary>

/// <param name="t"></param>

/// <returns></returns>

public string GetTime(Time t)

{

return string.Format("Received Time: {0}:{1}.{2}", t.Hour, t.Minute, t.Second);

}

}

public class Time

{

public int Hour { get; set; }

public int Minute { get; set; }

public int Second { get; set; }

}

Now, let us try to pass the values to the GetTime method using the Hour, Minute and Second values. This will throw the Object reference not set to an instance of an object exception.

Even though we have mentioned the values related to the fields of the Time object, API method is not able to map the values properly to the parameter. Now modify the code to include the [FromUri] attribute so it can handle the complex object from query string. As you can see in the following snippet, we include the [FromUri] attribute before specifying the Time object:

public string GetTime([FromUri] Time t)

{ -------------------}

Invoke the web API method with the same values before and observe the result, as shown in Figure 5.

image

Figure 6: Receiving successful results when calling the GetTime method