如何将Web API添加到现有的MVC Hottowel项目中

时间:2013-10-16 11:45:31

标签: asp.net-mvc-4 routing breeze hottowel

我使用Visual Studio中的模板创建了一个Hottowel项目。我想在该项目中添加Web API功能。我已经在控制器文件夹中创建了一个Web Api控制器并尝试访问"http://localhost:53397/api/Values",但是我收到错误,说The resource cannot be found错误。

我的控制器代码如下所示

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)
        {
        }
    }
}

我在APP_start文件夹中有一个名为BreezeWebApiConfig.cs的cs文件,其中包含映射路径的逻辑,如下所示。

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

如果我缺少Web APi的任何配置设置,请告诉我。

2 个答案:

答案 0 :(得分:1)

尝试装饰你的ApiController,如下:

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

有关详细信息,请查看breeze文档here

答案 1 :(得分:0)

您似乎正在制作错误的Url请求。查看WebApi的breeze路由配置。您需要像http://localhost:53397/api/Values/Get那样通过,因为微风正在使用基于控制器操作的路由。

希望这会有所帮助。