Shravan Kumar Kasagoni

Skip Navigation
Say Hello to ASP.NET Web API

Say Hello to ASP.NET Web API

 /  2 responses

ASP.NET MVC 4 now includes ASP.NET Web API, Which is formerly known as WCF Web API. In this article I am not digging into any details of Web API. I am going to explain through a sample how to create a Web API as part of ASP.NET MVC 4 solution. Web API is not just limited to ASP.NET MVC it can be part of ASP.NET WebForms solution.

HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.

ASP.NET Web API a new framework for creating HTTP services that can reach a broad range of clients including browsers and mobile devices. ASP.NET Web API is also an ideal platform for building RESTful services, I am listing the features of Web API from release notes.

  • Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a new, strongly typed HTTP object model. The same programming model and HTTP pipeline is symmetrically available on the client through the new HttpClient type.
  • Full support for routes: Web APIs now support the full set of route capabilities that have always been a part of the Web stack, including route parameters and constraints. Additionally, mapping to actions has full support for conventions, so you no longer need to apply attributes such as [HttpPost] to your classes and methods.
  • Content negotiation: The client and server can work together to determine the right format for data being returned from an API. We provide default support for XML, JSON, and Form URL-encoded formats, and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy.
  • Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects which can be used by the Web API actions.
  • Filters: Web APIs now supports filters, including well-known filters such as the [Authorize] attribute. You can author and plug in your own filters for actions, authorization and exception handling.
  • Query composition: By simply returning IQueryable<T>, your Web API will support querying via the OData URL conventions.
  • Improved testability of HTTP details: Rather than setting HTTP details in static context objects, Web API actions can now work with instances of HttpRequestMessage and HttpResponseMessage. Generic versions of these objects also exist to let you work with your custom types in addition to the HTTP types.
  • Improved Inversion of Control (IoC) via DependencyResolver: Web API now uses the service locator pattern implemented by MVC’s dependency resolver to obtain instances for many different facilities.
  • Code-based configuration: Web API configuration is accomplished solely through code, leaving your config files clean.
  • Self-host: Web APIs can be hosted in your own process in addition to IIS while still using the full power of routes and other features of Web API.

Let’s create an ASP.NET Web API sample. ASP.NET MVC 4 provides a template for creating Web API applications. It contains sample code with a Web API controller, but in this example we are going use plain ASP.NET MVC 4 Internet Application Template & create Web API sample. In this example I am going to use ASP.NET MVC 4 with Visual Studio 11 & .NET Framework 4.5. ASP.NET MVC 4 is built on top of .NET Framework 4,  so we can Visual Studio 2010 also for building the same demo.

  • Create a new ASP.NET MVC 4 Internet Application using New ASP.NET MVC 4 Project dialog
  • File => New => Project => In New Project Under Templates => Visual C# => Web => Choose ASP.NET MVC Web Application => [Change name of Project, Solution & Path of Location if required] => Click OK
  • Now New ASP.NET MVC 4 Project Dialog will pop up => select Internet Application => click OK
ASP.NET MVC 4 Internet Template
  • Let’s create a Speaker Entity under Models folder, which represents a speaker details in an event
Speaker Model
  • Now create a Web API Controller, Web API Controller can be create under any folder in the solution. But as a regular practice as of now I am creating it under same Controllers folder
  • Right click on Controllers folder => Add => New Item => select Web API Controller Class => name it as DevConSpeakersController => click Add
  • Above code snippet is the sample code generated for Web API Controller
  • If you compare it with regular ASP.NET MVC controller, Web API Controller is inherited from ApiController class instead of Controller class
  • ApiController class is available in System.Web.Http namespace
  • If we look at the methods in DevConSpeakersController, we can easily say they are also Http Verbs. As we are creating a Http service, instead of using fancy method name ASP.NET Web API simply uses the plain Http verbs for method names & they are mapped to respective Http requests
  • Still you  can use fancy method names, but we should either annotate with respective Http verb attributes or prefix method name with Http verb
  • Let’s  modify the implementation of Get method.  It will return list of speakers instead of list of strings, to do this I am not going to write any fancy logic (business logic / data access logic), I am simply returning a list of speakers as it is a simple demo
  • Build & debug the application (Hit F5), It will pop up the web browser with new modern ASP.NET MVC 4 Website
  • As we built a Http service, we don’t have any UI or code which is consuming the service, I am simple going to invoke it via URL in web browser
  • URL pattern as follows, application main URL http://{hotstname}:{portnumber}/ followed with postfix with /api/{webapi-controller-name}
  • Controller name is prefixed with “api”, this is to differentiate the web api routes from MVC/WebForms routes (if you don’t like the “api” prefix for controller name we can change it)
  • To handle Web API routes the following new entry routes.MapHttpRoute() is added into global.asax
  • URL looks like this http://localhost:{portnumber}/api/DevConSpeakers/
  • In URL we are not mentioning any Http method, so the default is Get method

The Web API invokes GetSpeakers() method & returns all the output as XML, but as we know Web API supports Content negotiation, we can request for data in desired format, JSON etc..

The above is a kind of hello world program demonstrates how to create Web API Controller & use Get request to fetch the data. For more information on Web API check,  stay tuned to my blog for more in-depth articles on ASP.NET Web API.

Write a response

Your email address will not be published.

All code will be displayed literally.