WCF, ASP.NET MVC, and the new ASP.NET Web API

If WCF and ASP.NET MVC had offspring it would be named ASP.NET Web API.  Like WCF, Web API is built for Web Service development.  Only instead of building on WCF data structures; Web API embraces a MVC style experience.  The result makes Web Service development more accessible to ASP.NET developers and gets WCF developers closer to HTTP. 

If MVC, WCF, and HTTP get your heart pumping; hop on the Web API thrill-ride.

Getting Started

Web API is part of the MVC 4 Beta.  The Web API install here is on the Web API home site http://www.asp.net/web-api. There are separate .NET 4.0 and .NET 4.5 releases.  Sample code from this article was done with the .NET 4.0 download.  The Web API template is under the “ASP.NET MVC 4 Web Application” project.  Like all .NET templates, creating a new project generates a working application.  As the product name indicates Web API is an ASP.NET experience.

MVC Revisited

As stated earlier Web API incorporates elements of WCF and MVC.  However, MVC is what a Web API developer first encounters.  The MVC core comprises Routes and Controllers.  A Web API application is indistinguishable from another MVC application.  First, there are Routes.

Web API Routes and MVC routes share the same classes.  Like MVC Routes Web API Routes are defined in the Global.asax.  Code from a sample Global.asax follows.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
 
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
 
 

Routes map to Actions on a Controller.  MVC conventions dictate that a component in the URL must map to the prefix name on a Controller class.  So, for example,  the URL “/api/values” maps to a Controller class called ValuesController.

Web API Controllers inherit from the ApiController class.  A sample Controller follows.

public class ValuesController : ApiController
{
    // GET /api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
 
    // GET /api/values/5
    public string Get(int id)
    {
        return "value";
    }
 
    // POST /api/values
    public void Post(string value)
    {
    }
 
    // PUT /api/values/5
    public void Put(int id, string value)
    {
    }
 
    // DELETE /api/values/5
    public void Delete(int id)
    {
    }
}
 

HTTP methods like GET and POST are processed by the Controller.  Web API conventions will map the HTTP method with a method name prefixed by the corresponding HTTP method name.  A developer can also apply attributes like HttpGet and HttpPost instead of following the conventions.

HTTP

A complete review of Web API HTTP support is beyond the scope of this article.  Instead I’ll highlight some core components.

Aside from new MVC components, Web API includes a new set of HTTP classes all contained in the System.Net.Http namespace .  Ultimately, HTTP messages are wrapped HttpRequestMessage and HttpResponseMessage classes.  Controllers are free to return whatever the desired format is.  For example, JSON has become a popular format because it works well with jQuery.

Web API includes Content Negotiation support.   Often a client will include a content format request in the header.  Where appropriate, Web API will attempt to fulfill a content request.

OData has become a popular standard.  Part of the OData specification defines a query syntax.  Controller methods returning an IQueryable interface will automatically support the OData query syntax.

MVC has certainly influenced the Web API experience.  Woven among the MVC components are patterns and concepts that WCF developers will be familiar with.

Formerly WCF Web API

Web API roots began in WCF Web API.  WCF Web API was merged into ASP.NET Web API.  WCF was built for agnostic transport.  In WCF changing a transport often means changing a binding.  WCF’s architecture hides the Transport details from the developer.  WCF continues to support HTTP (as a Transport), but the REST-like-URL experience of WCF Web API has been replaced with the new Web API MVC experience.

Nevertheless, there are some WCF ideas that have made their way into Web API.

WCF Influence

Developers coming from the WCF world expect rich extensibility points and self-hosting.  Web API does not disappoint.

Some WCF Channels can be thought of as a sort of Pipeline.  Channels may inspect incoming messages or inject information into a message header.  Web API sports a similar, but much lighter extensibility point called an HTTP Message Handler.  Message Handlers receive HttpRequestMessages or HttpReponseMessages.  Message handlers exist on the both the Client and Server components.  So both Client and Server can share the same message handler.

Web API also supports Self-hosting.  Self-hosting is common in WCF solutions.  Instead of living inside IIS; a Web API Server can run inside, for example, a Console Application.  Self-hosting is useful for not only unit testing, but also scenarios where an endpoint is needed inside, for example, a Desktop application.

Web API also supports the new Task based Asynchronous model. 

New Async

Like many components in the new .NET 4.5, Web API supports the new Task based Async model.  As mentioned earlier in the article Web API is supported under .NET 4.0 and .NET 4.5.  Though Async language features are new in C# 5.0 and .NET 4.5, Tasks were introduced in .NET 4.0.  Web API is a break with the past.  No more Asynchronous Programming Model.  If you are new to Tasks you’ll find a good introduction here http://www.codeguru.com/columns/experts/article.php/c17197/Understanding-Tasks-in-NET-Framework-40-Task-Parallel-Library.htm.

Conclusion

ASP.NET Web API is a new Microsoft HTTP Web Services platform.  Web API melds together ideas from WCF and ASP.NET MVC.  It sports a development experience much like the ASP.NET MVC experience.  Under the Web API hood is functionality more common in WCF.

Resources

Getting Started with ASP.NET Web API

ASP.NET Web API (Part 1)

Dan Roth on the new ASP.NET Web API

ASP.NET Web API released with ASP.NET MVC 4 Beta!

HTTP Message Handlers

System.Net.Http Namespace

ASP.NET MVC Controller Overview (C#)

RESTful Services With ASP.NET MVC

ASP.NET Web API



Related Articles

Comments

  • последние новости на сегодня

    Posted by FigoFlied on 02/08/2013 09:49am

    [url=http://www.rusarticles.com/poisk-v-seti-statya/novosti-i-novostnye-kanaly-v-internete-poslednie-novosti-na-segodnya-6446543.html]новости сегодня[/url] последние новости на сегодня новости сегодня [url=http://www.rusarticles.com/poisk-v-seti-statya/novosti-i-novostnye-kanaly-v-internete-poslednie-novosti-na-segodnya-6446543.html]последние новости на сегодня[/url] новости сегодня новости сегодня [url=http://www.rusarticles.com/poisk-v-seti-statya/novosti-i-novostnye-kanaly-v-internete-poslednie-novosti-na-segodnya-6446543.html]новости сегодня[/url] новости сегодня новости сегодня новости сегодня последние новости на сегодня

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Wednesday, September 24, 2014 8:00 AM - 9:00 AM PDT According to a recent Forrester Research report, many companies are choosing low-code platforms over traditional programming platforms, due to the speed with which low-code apps can be assembled and tested. With customer-facing applications on the rise, traditional programming platforms simply can't keep up with the "short schedules and rapid change cycles" required to develop these applications. Check out this upcoming webinar and join Clay Richardson from …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds