Professional ASP.NET MVC 4
by Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen, Scott Hanselman
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access