1

我正在尝试将 ASP.NET Web API(来自 MVC 4)添加到我的项目中.....但是我在从 Area/WebAPI/Controller 获得任何响应时遇到了一些麻烦(不太确定哪里出错了...)

我安装了路线调试器,如果我转到我的主页...我看到了路线...

Matches Current Request Url Defaults    Constraints DataTokens


    False   api/{controller}/{action}/{id}  action = Index, id = UrlParameter.Optional  (empty) Namespaces = OutpostBusinessWeb.Areas.api.*, area = api, UseNamespaceFallback = False
    False   {resource}.axd/{*pathInfo}  (null)  (empty) (null)
    True    {controller}/{action}/{id}  controller = Home, action = Index, id = UrlParameter.Optional   (empty) (empty)
    True    {*catchall} (null)  (null)  (null)

所以似乎路线已设置

接下来我在“api”区域有一个PlansController,它只是“Add New”生成的默认apiController......

public class PlansController : 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(string value)
    {
    }

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

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

现在当我去http://localhost:2307/api/Plans/1

我明白了

Server Error in '/' Application.
The resource cannot be found.    
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 
    Requested URL: /api/Plans/1

任何想法为什么?有什么我需要配置的吗?

4

2 回答 2

3

ASP.NET MVC 4 在开箱即用的区​​域不支持 WebApi。

Martin Devillers 提出了一个解决方案:ASP.NET MVC 4 RC: Getting WebApi and Areas to play nicely

您还可以在我对类似问题的回复中获得更多详细信息(特别是对于便携式区域的支持): ASP.Net WebAPI area support

于 2012-07-17T17:51:27.037 回答
2

将其更改为:

    // GET /api/<controller>
    public IEnumerable<string> GetMultiple(int id)
    {
        return new string[] { "value1", "value2" };
    }

调用它:

http://localhost:2307/api/Plans/GetMultiple/1

这是我的 Global.asax:

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

我的控制器:

   public class MyApiController : ApiController
   {
      public IQueryable<MyEntityDto> Lookup(string id) {

        ..
   }

我这样称呼它:

    http://localhost/MyWebsite/api/MyApi/Lookup/hello

完美运行。

于 2012-04-23T23:48:25.653 回答