Starting with Web API in ASP.NET MVC

Web API is the perfect platform for building RESTful applications on the .NET Framework. If you want to build HTTP services that can reach any kind of client, Web API is what you need. Many developers are confused and cannot understand the differences between the usual MVC Controllers and the API controllers in ASP.NET MVC Framework. This post, is the start up post of the blog’s Web API series and it’s going to show you what you need to create a Web API application from scratch. More specifically we will create a project to see which classes and assemblies are needed to create Web API applications and another one, to demonstrate consuming Web API services. You will need a tool to capture the traffic exchanging each time you consume the service, and Fiddler is my recommendation.

Start by creating a new ASP.NET Empty Web Application project in Visual Studio. Name the project “WebAPIFromScratch”. Most of you will know that there are specific templates in Visual Studio for building Web API applications but my intention here is to show you what you need to include in a project to support Web API. Right click the project and select Manage NuGet Packages…. Click the Online tab and search for Web-API. Select and install the first one as follow.

startwithwebapi_1
Close the window when the installation is finished and create a new C# class named FirstWebAPIController. Change it’s contents to the following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Http;

namespace WebAPIFromScratch
{
    public class FirstWebAPIController : ApiController
    {
        public string Get()
        {
            return  "Message from my FirstWebAPI controller";
        }
    }
}

Pay attention to the base class we used, the ApiController. Every time you need to create an API controller your controller class must inherit from that base class. This class exists in the System.Web.Http namespace which in turn, is included in the assemblies you added when you run the previous installation. The above controller has a Get() action method which can be invoked from HTTP GET Requests. There is one more thing we need to do. Tell the Framework how to route and match specific URLs to our GET action method. To do that, right click your project and add a Global Application Class file, keeping it’s default name “Global.asax”. In the “Application_Start” method we will define how the routing in our application works. Change that method’s contents as follow.

using System.Web.Http;
using System.Web.Http.Routing;

namespace WebAPIFromScratch
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            GlobalConfiguration.Configuration.Routes.Add("default", 
                new HttpRoute("{controller}"));
        }

        // Rest of the code ommited

You can add a Route using the GlobalConfiguration.Configuration.Routes.Add method, passing as parameters, a name for this new route and an HttpRoute object which defines the actual routing. Here we defined that to reach a Web API controller’s action all you need to do, is pass the controller’s name. Build your application and run it. At this point you will get a HTTP Error 403.14 – Forbidden error since we haven’t defined a default controller for application. That’s ok though, just add a /FirstWebAPI to your URL and see the results.

startwithwebapi_2
You have finally invoked your Web API controller’s action. Open Fiddler and start capturing. While at the “Inspectors” tab request from your browser the same URL. Double click the respective row in Fiddler and watch it’s contents.

startwithwebapi_3
If you don’t see the above results you probably have request the URL from different broswer (IE maybe?). Let’s see know how to invoke another controller’s action. Add another C# class file named SecondWebAPIController changing it’s contents as follow.

using System.Web.Http;

namespace WebAPIFromScratch
{
    public class SecondWebAPIController : ApiController
    {
        public string Get()
        {
            return "Message from my SecondWebAPI controller";
        }
    }
}

Build your application, go to Fiddler’s composer tab and request the second controller’s action as follow.

http://localhost:your_port_number/SecondWebAPI

Double click the respective row again and see the results in the inspector tab. You will get the new controller’s message instead of the first one. Now let’s try something else. Right click your solution and add a new project. This time select ASP.NET MVC 4 Web Application naming it “WebAPITemplate” and selecting Web API in the next window of the wizard. When the project has been created make sure you set this project as the start up. Visual Studio created for you all the structure you need to start building an ASP.NET MVC application using all the Web API functionality. The ValuesController controller class inside the “Controllers” folder is a Web API controller. You can see that by default, has some action methods to support GET, POST, PUT and DELETE HTTP requests. We will change a little it’s contents in order to use some mock data for our demonstration.

public class ValuesController : ApiController
    {
        static List<string> mock_data = initMockData();

        private static List<string> initMockData()
        {
            var ret = new List<string>();
            ret.Add("Product - 1");
            ret.Add("Product - 2");
            ret.Add("Product - 3");
            ret.Add("Product - 4");
            return ret;
        }

        // GET api/values
        public IEnumerable<string> Get()
        {
            return mock_data;
        }

        // GET api/values/5
        public string Get(int id)
        {
            return mock_data[id];
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
            mock_data.Add(value);
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
            mock_data[id] = value;
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
            mock_data.RemoveAt(id);
        }
    }

Build and start your application. This time you will see a start up page but never mind. Add a /api/values to the default URL and check your browser response.
startwithwebapi_4
The requested URL has matched the Route that Visual Studio has created for you, in the WebApiConfig.cs. Add /1 to the URL to get the second product in the mock_data list.

startwithwebapi_5
Web API will match by default any GET HTTP request to an action that it’s name starts with GET.. and depending on additional parameters will match specific version of those GET named actions. The same story with the others HTTP verbs. If a POST HTTP request is made, Web API will try to match a controller’s action method, whose name start with POST.. You can always name your action methods whatever you need, but if you do so, you will have to add respective attributes above them, like [HttpPost] in order Web API to make the respective match. If you want to try a POST request, go to Fiddler’s composer tab, put the respective URL, select POST as the HTTP method and make sure you add a Content:Type: application/json definition. In the Requested Body add a string ‘Product – 5’ and click execute.
startwithwebapi_6
Do not expect to see any particular results in Fiddler but go and request all the products again in your browser or the fiddler as you did before. This time you will see that a Product – 5 has been committed to the mock_data list. Try now from Fiddler to delete the first product and then request all the products again.

startwithwebapi_7
That’s it for now. We have seen how URL’s are matched to specific Web API controller’s actions through the HTTP method Verbs. Though, we requested POST and DELETE HTTP requests through Fiddler when you probably are going to do this from your web pages. We are going to dive into Web API development more in later posts so keep in touch. I hope you enjoyed the post.

Advertisements


Categories: ASP.NET

Tags: , ,

4 replies

  1. Thanks for the post, Christos.

    I was wondering about the step to add the Microsoft Web API NuGet package. Did you need to do that for the “WebAPIFromScratch” project because you were developing it in VS 2010 and not VS 2012? Isn’t Web API already “built in” to VS 2012? Hope you can clarify this for me.

    • Hi Norm, well first of all mind that all my projects are being developed in VS 2012 so you can exclude that reason. The answer is that YES, Web API is kind of “build in” feature in VS 2012 but isn’t by default installed in all kind of Web project templates. In other words, if you choose to create an ASP.NET MVC Application choosing the Web API template, you wouldn’t have to install Microsoft Web API NuGet package, since Web API would have been already installed for you. In this post though, we chose to create simply an ASP.NET Empty Web Application which by default, hasn’t installed that features. This way , we saw which packages and classes are needed in order to add Web API controllers in an empty web application. I hope I made it clear for you now.

Trackbacks

  1. Web API basic CRUD Operations following HTTP principles « chsakell's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Diary Of A Programmer

Because every day is worth noting

Chara Plessa

The purpose of this blog is to broaden my education, promote experimentation and enhance my professional development. Albert Einstein once said that “If you can’t explain it simply, you don’t understand it well enough” and I strongly believe him!

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Kumikoro

A Front End Developer's Blog

Muhammad Hassan

Full Stack Developer | ASP.NET | MVC | WebAPI | Advanced Javascript | AngularJS | Angular2 | C# | ES6 | SQL | TypeScript | HTML5 | NodeJS, MS candidate @LUMS, Grad & EX-Adjunct Faculty @NUCES-FAST, seasonal blogger & open-source contributor. Seattle, WA.

Software Engineering

Web development

IEvangelist

.NET, ASP.NET, C#, MVC, TypeScript, AngularJS

leastprivilege.com

Dominick Baier on Identity & Access Control

Happy DotNetting

In Love with Technology

Knoldus

Knols of experience to your advantage

knowshnet

Search - Read - Request - Share

Rahul's space

Learn, Share and Grow with me !

Dhananjay Kumar

Developer Evangelist @Infragistics | MVP @Microsoft |

SQL Authority with Pinal Dave

SQL Server Performance Tuning Expert

Conficient Blog

Random bits of tech from @conficient

Code! Code! Code!

SOLID & KISS

Code Wala

Designing and coding

Microsoft Mentalist

A way to start with Microsoft Technologies

Tony Sneed's Blog

A glimpse into the lives of Tony & Zuzana Sneed

%d bloggers like this: