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

By | September 29, 2013
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest

Introduction to ASP.NET Web API

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 while going through this ASP.NET Web API Tutorial, 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
You are designing an ASP.NET Web API application. You need to select an HTTP verb to allow blog administrators to moderate a comment. Which HTTP verb should you use?

  • A. GET
  • B. POST
  • C. DELETE
  • D. PUT

To further test your ASP.NET Web API skill, Take a Complete FREE Online Test or MCSD Practice Exam: 70-486 (Developing ASP.NET MVC Web Applications). Simply Click Here.

 Correct Answer: D

Let’s move forward step by step to create a simple HTTP service using ASP.NET Web API.

ASP.NET Web API Tutorial with Simplified Approach

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.
ASP.NET Web API Project
Web API Tutorial Template
  • 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 in this asp.net web api tutorial, 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”.
Model for Web API
Product Model
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”.
Product Controller in Web API Tutorial
First Web API Service
  • Click the “Add” button, a new controller class will be added.
More Web API Tutorial
In order to make the things simple, we will load the model with data inside this controller instead of loading it from database. You can easily find more Web API Tutorial here that explains the process to fetch the records 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:

Output for ASP.NET Web API Service

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.

Rendered Content for Web API Service
Final output returned can be displayed differently by different browsers. Here is the output of google chrome version 29.0.1547.66.
You are working as a Web API developer with WebDevTutorials. You have developed a Student HTTP Service using ASP.NET Web API technology and you want to return a View from Web API method.

  • A. Use ViewBag.
  • B. Use Partial View against Web API method.
  • C. You can’t return view from ASP.NET Web API method.
  • D. None of Above.

To further test your ASP.NET Web API skill, Take a Complete FREE Online Test or MCSD Practice Exam: 70-486 (Developing ASP.NET MVC Web Applications). Simply Click Here.

 Correct Answer: C

Hopefully, this simple web api 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.

ASP.NET MVC & Web API Jobs [Updated Daily]

Top ASP.NET MVC Jobs

Web Developer
Source: Indeed
Details: Have worked with the .NET web stack including ASP.NET, MVC, WebAPI 2 and C#. We are seeking a driven, innovative and detail-obsessed software developer who...  More
22 hours ago

Bellevue, WA 06-December-2016

Web Developer (C# & AngularJS) -2 months of contract
Source: CSI Interfusion Inc
Details: Solid skills on C#, ASP.Net, MVC, JavaScript, CSS, HTML, etc. CS I Interfusion ( CSI ) (size:....  More
5 days ago

Redmond, WA 02-December-2016

Backend Web Developer
Source: Indeed
Details: Minimum 4 years experience with writing WinAPI/RESTFul API and working in an ASP.NET MVC environment. Keyventer is seeking a *Back End Web*....  More
8 days ago

Seattle, WA 28-November-2016

Web Developer (C# & AngularJS) - 2 months
Source: Indeed
Details: *CS* *I Interfusion* ( *CSI* ) (size: 20,001+ employees, globally), a leading global provider of *IT consulting services, technical services* and *outsourcing...  More
14 days ago

Redmond, WA 23-November-2016

Programmer / Analyst
Source: Intel
Details: Advanced forms with dynamic connection to stored procedures on other databases - Experience in database design and data modeling - Experience with developing...  More
5 days ago

Hillsboro, OR 97124 02-December-2016

Programmer Analyst
Source: AIG
Details: Strong knowledge of .Net Framework, C#, ASP.Net, MVC, LINQ, Visual Studio 2008/2010/2013 and Version Control System (TFS, Git etc.)....  More
30+ days ago

Jeffersonville, IN 16-September-2016

Web Application Developer
Source: Indeed
Details: ASP.NET MVC, Web Forms, Web API. SC Strategic Solutions is looking for passionate full time software developers who are efficient problem solvers with a...  More
14 days ago

Norwalk, OH 23-November-2016

Web Developer
Source: Indeed
Details: MVC:. ASP.Net MVC and C#.Net experience a must*. ~~~~~NOT A REMOTE POSITION~~~~~*....  More
14 days ago

Sarasota, FL 34232 23-November-2016

Front End Developer | Web Mobile
Source: Specialists On Call
Details: AngularJS, HTML5, Sass, C#, ASP.Net MVC, SOA. Specialists On Call, Inc....  More
15 days ago

Reston, VA 20190 21-November-2016

Microsoft web developer - Contract - Telecommuting
Source: Indeed
Details: MVC, .Net, CSS, HTML:. Working familiarity with ASP.net, MVC. This is a 3 months + contract position for our direct client based in San Antonio....  More
18 days ago

San Antonio, TX 19-November-2016

.NET Developer Instructor
Source: Indeed
Details: NET – You are comfortable working with ASP.NET, MVC and Core Web API. About Coder Camps:....  More
19 hours ago

Redmond, WA 07-December-2016

e-Commerce Web Developer
Source: Indeed
Details: Hands-on code development experience in web development field using ASP.NET MVC, C#, HTML 5.0, jQuery, XML, CSS, and Web Services....  More
21 days ago

South Saint Paul, MN 55075 16-November-2016

Back-End Web Developer
Source: DNTG Software
Details: Experiences with ASP.NET and MVC in C#, Web API. Develop and maintain secure and stateless web services using Microsoft ASP.NET MVC 4.0 based on the REST...  More
21 days ago

Buena Park, CA 16-November-2016

Web & Mobile Developer
Source: Indeed
Details: Our software stack includes Xamarin C# on iOS & Android, ASP.NET MVC, Microsoft Azure, Angular.js, HTML5, and JavaScript....  More
21 days ago

Kent, WA 15-November-2016

.Net Developer with Azure Cloud Experience
Source: CSI Interfusion Inc
Details: Demonstrated experience working on services built using ASP.NET / MVC, and SQL db. CSI Interfusion (CSI) (size:....  More
5 days ago

Redmond, WA 02-December-2016

Senior Software Engineer
Source: Clarity Consulting Inc.
Details: C# / WinRT / .NET / XAML / Windows 8/8.1 / Windows Phone 8/8.1 / Xbox / UCMA/UCWA / iOS / Cocoa Objective-C / Android / Xamarin / HTML5 / JavaScript/jQuery /...  More
1 day ago

Seattle, WA 06-December-2016

.Net Developer
Source: Indeed
Details: .Strong Experience developing MVC applications using ASP.Net MVC. .4+ years experience in software engineering....  More
7 days ago

Redmond, WA 30-November-2016

Web Developer
Source: Indeed
Details: Experience with ASP.NET MVC is a plus. R+L Carriers is currently seeking a Web Application Developer for our Ocala, FL Technical Center and our Wilmington, OH...  More
29 days ago

Wilmington, OH 45177 08-November-2016

.Net Developer
Source: Indeed
Details: .Strong Experience developing MVC applications using ASP.Net MVC. Essential Job Functions....  More
41 minutes ago

Seattle, WA 07-December-2016

Front-End Web Developer
Source: Indeed
Details: Experience with the MS development stack Visual Studio, .NET, ASP.NET MVC, etc. Crystal Capital Partners, a financial services company w/ over 20 years of...  More
30+ days ago

Miami, FL 04-November-2016

Web Applications Developer
Source: ITR (Information Technology Resources)
Details: Experience with the MVC pattern and responsive design of web applications. Web Applications Developer....  More
30+ days ago

Oak Ridge, TN 02-November-2016

Web Developer
Source: Indeed
Details: Experience with ASP.NET MVC is a plus. R+L Carriers is currently seeking a Web Application Developer for our Ocala, FL Technical Center and our Wilmington, OH...  More
29 days ago

Ocala, FL 08-November-2016

Senior Developer
Source: Indeed
Details: .NET architecture, ASP.NET MVC, OOP, SOA, repository patterns (CRUD). Development, maintenance and administration as part of a team supporting advanced...  More
2 hours ago

New York, NY 07-December-2016

Senior Software Developer
Source: MediaRadar
Details: Knowledge of ASP.NET MVC 4/5. Web based projects will center on ASP.Net MVC 4 and the Razor view engine, with Angular.js....  More
20 days ago

New York, NY 17-November-2016

Programmer Analyst
Source: Kindred Healthcare
Details: Have experience with ASP.NET MVC and/or WPF. Clinical Systems Development....  More
19 days ago

Louisville, KY 40202 18-November-2016

Top 10 Interview Questions and Answers Series:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest
Category: ASP.NET Web API Tags: , ,

About IMRAN ABDUL GHANI

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, and www.sharepointfordummies.net.

  • wow…seems great

  • Really great post .. thanks sharing your topic

    website

  • Thanks very much… I m waiting for CRUD operations using Web API…. Thanks again….

  • 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’.

  • 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 }
    );

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

    • 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.

  • This comment has been removed by a blog administrator.

  • swapna

    i am getting error as MvcApplication1.Controllers.productsController.Product’ is a ‘field’ but is used like a ‘type. Plzz help me out in this problem

    • I believe you are making some mistake while calling a method. This type of error occurs normally when someone calls a method at class level instead of making call inside a method.

  • Above are around 52 errors, If you can remove others, hopefully things will be clear but it seems you have some wrong placement of methods (outside class) etc.

  • Roman Denysiuk

    IMRAN, could you tell me the way how to allow update/delete/create records (through web service) only for authenticated users?

  • Edwin Yesid Castañeda Henao

    Imran, this blog is excellent. Conglaturations !!

  • user2083

    well explained! easy to understand for a newcomer.

    here one thing i want to mention is while executing above given example my browser was showing below error :

    “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:45788/api/products’.

    No type was found that matches the controller named ‘products’.

    And the reason i found was, in my application, ‘ProductsController’ class was by default inheriting “Controller” as base class as given below:

    “public class ProductsController : Controller”

    instead of ‘ApiController’ class as shown in above example code.

    So After adding namespace “using System.Web.Http;” in ‘ProductsController’ class and inheriting ‘ApiController’ as base class as follows:

    “public class ProductsController : ApiController”

    it worked.

    thanks again for this good piece of work.

  • user2083

    well explained! easy to understand for a newcomer.

    one thing i want to mention, while executing above given example browser was showing below error :

    “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:45788/api/products’.

    No type was found that matches the controller named ‘products’.

    And the reason i found was, in my application, ‘ProductsController’ class was by default inheriting “Controller” as base class as given below:

    “public class ProductsController : Controller”

    instead of ‘ApiController’ class as shown in above example code.

    So After adding namespace “using System.Web.Http;” in ‘ProductsController’ class and inheriting ‘ApiController’ as base class as follows:

    “public class ProductsController : ApiController”

    it worked.

    thanks again Imran for this good piece of work.