Search code examples
asp.net-mvc-4routesbreezehottowel

How to add web API to an existing MVC Hottowel project


I have one Hottowel project created using it's template from Visual Studio. I want to add the Web API feature in that project. I have created a Web Api controller to the controller folder and tries to access like "http://localhost:53397/api/Values" But I get an error saying The resource cannot be found error.

My controller code looks like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MvcApplication8.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}

I have the cs file in APP_start folder called BreezeWebApiConfig.cs which contains the logic to map the route like below.

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
          name: "BreezeApi",
          routeTemplate: "api/{controller}/{action}"
      );

Let me know If I am missing any configuration setting for Web APi.


Solution

  • Try to decorate your ApiController like bellow :

    [BreezeController]
    public class NorthwindIBModelController : System.Web.Http.ApiController {
    
        readonly EFContextProvider<NorthwindIBContext> ContextProvider =
             new EFContextProvider<NorthwindIBContext>();
    
        [HttpGet]
        public String Metadata() {
          return ContextProvider.Metadata();
        }
    
        [HttpPost]
        public SaveResult SaveChanges(JObject saveBundle) {
          return ContextProvider.SaveChanges(saveBundle);
        }
    
        [HttpGet]
        public IQueryable<Customer> Customers() {
          return ContextProvider.Context.Customers;
        }
    

    For more information have a look to breeze documentation here.