Writing an API Controller

Web API ships with MVC, and both utilize controllers. However, Web API does not share the Model-View-Controller design of MVC. They both share the notion of mapping HTTP requests to controller actions, but rather than MVC's pattern of using an output template and view engine to render a result, Web API directly renders the resulting model object as the response. Many of the design differences between Web API and MVC controllers come from this core difference between the two frameworks. This section illustrates the basics of writing a Web API controller and actions.

Examining the Sample ValuesController

Listing 11-1 contains the ValuesController that you get when you create a new project using the Web API project template. The first difference you'll notice is that there is a new base class used for all API controllers: ApiController.

Listing 11.1: ValuesControllers

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

namespace WebApiSample.Controllers
{
    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([FromBody] string value) {
        }
        // PUT api/values/5
        public void Put(int id, [FromBody] string value) {
        }
        // DELETE api/values/5
        public void Delete(int id) {
        }
    }
}

The second thing you'll ...

Get Professional ASP.NET MVC 4 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.