O'Reilly logo

Professional ASP.NET MVC 4 by Scott Hanselman, K. Scott Allen, Brad Wilson, Phil Haack, Jon Galloway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required