How to use ApiControllers with your current MVC Application

By | August 26, 2014

Like me you might be starting to integrate AngularJS or any other JS Framework in your MVC Application then later on finding out you are converting a lot of your results to handle this calls.  While it works with the MVC Controllers you always have to serialize your result to JSON Format and enabling client GET requests like this.

1 Return JSON


So how do you avoid it?

By using API Controllers.

So whats the difference between the two? Its simple, Controllers returns a View while ApiController returns serialized data for the client.  Now it makes more sense why you would use it right? because if you use any JavaScript frameworks that grabs data then ApiControllers makes more sense as it is designed for it.  The are specialized in returning data and it takes care of transparently serializing the data into the format requested by the client. They also provide REST-ful API as they follow a different routing scheme by default.  Having said that Controller can also do this but you have to do a lot of manual coding just to achieve it.

Now how do you add this if I already have a current MVC Application? Well if you are starting from scratch there is an option by choosing Web API project like such

2 Web API

But if you have a project already running then follow this steps.

  1. Add reference to System.Web.Http.WebHost.
    3 Add WebHost Reference
  2. Create a new class called WebApiConfig.cs in App_Start Folder
    4 New WebApi Class
    then Register your routes like such

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration configuration)
        {
            configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            configuration.Routes.MapHttpRoute(
                    "DefaultApi",
                    "api/{controller}/{id}",
                    new { id = RouteParameter.Optional }
                );
        }
    }
  3. Modify Global.asax.cs to RegisterWebApiConfigurationFirst is by Adding a reference to System.Web.HttpThen registering theWebApi Configuration like such
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    

    5 Modify Global ASAX

  4. Now use it and its as simple as this
    public class BrandController : ApiController
    {
          
        // GET api/
        public IEnumerable<string> Get()
        {
            return new string[] { "value1""value2" };
        }
     
        // GET api//5
        public string Get(int id)
        {
            return "value";
        }
     
        // POST api/
        public void Post([FromBody]string value)
        {
        }
     
        // PUT api//5
        public void Put(int id, [FromBody]string value)
        {
        }
     
        // DELETE api//5
        public void Delete(int id)
        {
        }
    }
  5. Then you are ready to try itThis is the Get(int id) result
    6 Result 2
    This is the Get result
    6 Result
    If you notice thy are XML results, and if you want to output as JSON you just need to add this line to your WebApiConfig Class

    configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    

    So it should look like this

    public static void Register(HttpConfiguration configuration)
    {
        configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
     
        configuration.Routes.MapHttpRoute(
                "DefaultApi",
                "Api/{controller}/{id}",
                new { id = RouteParameter.Optional }
            );
    }

    and instead of returning string and string arrays you can return the ViewModel that you are already using in your current MVC project and it will convert it to JSON

    // GET Api/<controller>
    public IEnumerable<BrandViewModel> Get()
    {
        var result = brandQuery.GetAll();
        return result;
    }
     
    // GET Api/<controller>/5
    public BrandViewModel Get(int id)
    {
        var result = brandQuery.Get(id);
        return result;
    }


One thought on “How to use ApiControllers with your current MVC Application

  1. Pingback: Using Angular JS with your Current MVC Application | Raymund Macaalay's Dev Blog

Leave a Reply