Click here to Skip to main content
15,886,110 members
Articles / MVC

How to use ApiControllers with your current MVC Application

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
15 Sep 2014CPOL2 min read 15.6K   4  
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 enablin

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;
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
New Zealand New Zealand
http://nz.linkedin.com/in/macaalay
http://macaalay.com/

Comments and Discussions

 
-- There are no messages in this forum --