ASP.NET Web API      Interview Questions         HTML 5                               jQuery                              ASP.NET MVC framework

Saturday, September 28, 2013

3 simple steps to create your first ASP.NET Web API service

"ASP.NET Web API is a framework that simplifies the creation of HTTP services".
Using ASP.NET Web API we can create HTTP services those are non-SOAP based like plain XML or JSON strings etc. with added advantages.
  • Allowing to create resource-oriented services using the full features of HTTP.
  • Exposing services to a variety of clients easily like browsers or mobile devices etc.
Before diving into details, I would like to clarify one misconception that ASP.NET Web API has replaced WCF. WCF is still a powerful programming model for creating SOAP based services that use a variety of transport protocols like HTTP, TCP, Named Pipes or MSMQ etc. You can find the same implementation by using WCF REST in another article i.e. "5 simple steps to create your first RESTful service"

>>Creating ASP.NET Web API service that supports CRUD (Create, Retrieve, Update, Delete) operations<<
Apart from Visual Studio 2010 or 2012, we also need MVC 4.0 to implement this HTTP service. For the purpose of this implementation, I am going to use Visual Studio 2010.
You can download MVC 4.0 for Visual Studio 2010 from Microsoft as follows:

Following are 3 simple steps to create HTTP service that returns non-SOAP based data.
  • Create Web API Project
  • Prepare domain Model
  • Adding Controller class
Let's move forward step by step to create a simple HTTP service using ASP.NET Web API.

1. Create Web API Project
  • Open Visual Studio and create "New Project" i.e. File -> New Project.
  • Choose "ASP.NET MVC 4 Web Application" template and name project as "FirstWebAPIService".
  • When you click "OK" button, a new window will appear for selecting a sub-template. Actually for ASP.NET MVC 4 Web Application, we have multiple sub-options i.e. Empty, Internet Application, Web API etc.
  • Choose "Web API" and simply press "OK" button.

  • A default ASP.NET MVC 4 Web API template project is created. As its an MVC application template, so you will easily find "Model", "View" and "Controller" folders inside it.
2. Preparing domain Model
Now in a second step, we need to prepare the model.
  • Right click on the "Model" folder and choose "Class" under "Add" from the context menu as shown in figure.
  • Name the class as "Product.cs".


Here is the code for Product class.

    public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public string ProductCategory { get; set; }
        public int Price { get; set; }
    }

3. Adding Controller Class
Controller class plays an important role, because request coming from client hits the controller first. Then the controller decides which model to use to serve the incoming request. So, in order to add a controller:

  • Right click on the "Controller" folder and choose "Controller" under "Add" from the context menu as shown in figure.
  • Name the controller as "ProductsController".

  • Click the "Add" button, a new controller class will be added.
In order to make the things simple, we will load the model with data inside this controller instead of loading it from database. Following is the code for controller class.

public class ProductsController : ApiController
{
        Product[] products = new Product[]
         {
             new Product { ProductID = 1, ProductName = "Product 1", ProductCategory= "Category 1", Price = 120 },
             new Product { ProductID = 2, ProductName = "Product 2", ProductCategory= "Category 1", Price = 100 },
             new Product { ProductID = 3, ProductName = "Product 3", ProductCategory= "Category 2", Price = 150 },
             new Product { ProductID = 4, ProductName = "Product 4", ProductCategory= "Category 3", Price = 90 }
         };

        public IEnumerable<Product> GetProducts()
        {
            return products;
        }
}

Don't forget to add "using FirstWebAPIService.Models;" at the top of the controller class.

Now, it's time to test your HTTP service using ASP.NET MVC Web API.
Run the application by pressing "CTRL+F5", Welcome window will appear as follows:


In order to call our Product controller, change the URL as "http://localhost:XXXX/api/products". You will see the results as shown in following output window.

Final output returned can be displayed differently by different browsers. Here is the output of google chrome version 29.0.1547.66.


Hopefully, this simple web development tutorial will be helpful for developers to code their first HTTP service using ASP.NET MVC Web API. Further, for performing all CRUD operations using Web API, Follow the click.



Be social and share with others via:



Related Web Development Tutorials:

By Imran Abdul Ghani
Software Developer (Senior)
United Arab Emirates
Imran Abdul Ghani is working as Software Developer(Senior) with extensive knowledge in Web development technologies especially C#, ASP.NET, MVC, WCF, Web API, ADO.NET Entity Framework, jQuery etc. He has several years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET (MCSD.NET) since 2005. You can reach his blogging at www.webdevelopmenthelp.net & www.topwcftutorials.net.

11 comments:

  1. Really great post .. thanks sharing your topic

    website

    ReplyDelete
  2. Thanks very much... I m waiting for CRUD operations using Web API.... Thanks again....

    ReplyDelete
    Replies
    1. Hi Jalpan,
      Hopefully you have already checked out CRUD operations already at following URL.
      --------------------------------------
      http://www.topwcftutorials.net/2014/01/CRUD-WCF-RESTful-Service.html
      -----------------------------

      Delete
  3. Easy to do tutorial. Thanks mate however I am having this error when I run the program:

    This XML file does not appear to have any style information associated with it. The document tree is shown below.


    No HTTP resource was found that matches the request URI 'http://localhost:59074/api/products'.


    No type was found that matches the controller named 'products'.

    ReplyDelete
  4. Dear Abraham,
    You need to check you configuration and verify the routeTemplate as follows:
    1. Open WebAPIConfig.cs file under "App_Start" folder in Visual Studio.
    2. Inside Register method, routeTemplate value should be equal to "api/{controller}/{id}".

    As I have the following:
    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );

    ReplyDelete
    Replies
    1. Thanks for the swift reply Imran.
      It looks like I have the same settings under Register Method, find code below:

      public static void Register(HttpConfiguration config)
      {
      config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = RouteParameter.Optional }
      );

      Delete
    2. Abraham, Kindly follow the thread.
      http://forums.asp.net/t/1916587.aspx?WebAPI+No+HTTP+resource+was+found+that+matches+the+request+URI

      Delete
  5. when i try this...everything was ok till chnging url bt when i change url it land at google search page ...why this??

    ReplyDelete
    Replies
    1. Dear Nilam,
      Kindly look for my above comments on Abraham query. You might need to update routeTemplate.

      If it doesn't resolve your issue, kindly elaborate your issue a bit more.

      Delete
  6. This comment has been removed by a blog administrator.

    ReplyDelete