WebApi development using MVC

In this post I am going to discuss some of the lessons learned during my initial days of learning MVC WebApi framework. Microsoft has done a wonderful job with tutorials on writing WebApi using MVC 4 framework. While following some of these tutorials I ran into some issues that required little bit more information that was not obvious in the tutorials or the author assumed that user already knew about it. So this post is more to complement what is already available on Asp.Net site.

WebApi Namespaces

One of the first thing you will notice is the controller is derived from ApiController and not Controller class defined in System.Web.Mvc namespace. When you write WebApi you are including following core namespaces in your code.

using System.Net;
using System.Net.Http;
using System.Web.Http;

This does not mean that these are only namespaces you will need. But these are the core ones that implement most of WebApi framework.

Dependency Injection (DI) in WebApi

If you have been developing MVC based web application, you are used to providing your own dependency injection implementation by setting your object in DependencyResolver. The code probably looks something as shown below.

DependencyResolver.SetResolver(TradingDiResolver);
    

In WebApi, you are still hooking your DI implementation in Global.asax when the application starts. But you will use GlobalConfiguration. The code will look something like shown below.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

   GlobalConfiguration.Configuration.DependencyResolver =
         new Trader.Services.Infrastructure.ServiceDiResolver();
 
    WebApiConfig.Register(GlobalConfiguration.Configuration);
   FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
   RouteConfig.RegisterRoutes(RouteTable.Routes);
   BundleConfig.RegisterBundles(BundleTable.Bundles);
}
    

In normal practice i will move the code for DI in WebApiConfig.Register method. I have left it in Global.asax.cs class just for illustration.

Routing in WebApi

For WebApi, routing is set in HttpConfiguration using same mechanism as I described for DI. When you create new WebApi project, you will notice that you have class WebApiConfiguration under App_Start folder. Application calls following code from Global.asax.cs to configure WebApi related settings.

WebApiConfig.Register(GlobalConfiguration.Configuration);
    

So any changes you need to make to routing for WebApi, you will be making it in WebApiConfig.cs and not in RoueConfig.cs.

These are some of the basic things that you will need to watch out for when starting writing WebApi using MVC 4. In upcoming posts I will discuss more details about WebApi development using MVC framework.

Search

Social

Weather

-0.4 °C / 31.3 °F

weather conditions Clouds

Monthly Posts

Blog Tags