How to use ApiControllers with your current MVC Application





5.00/5 (2 votes)
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.
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
But if you have a project already running then follow this steps.
- Add reference to System.Web.Http.WebHost.
- Create a new class called WebApiConfig.cs in App_Start Folder
then Register your routes like suchpublic 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 } ); } }
- Modify Global.asax.cs to RegisterWebApiConfigurationFirst is by Adding a reference to System.Web.HttpThen registering theWebApi Configuration like such
WebApiConfig.Register(GlobalConfiguration.Configuration);
- 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) { } }
- Then you are ready to try itThis is the Get(int id) result
This is the Get 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 Classconfiguration.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; }