从区域中的 asp.NET WebAPI 获取响应时遇到问题



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

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

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"

区域有一个计划控制器,它只是"添加新"生成的默认 api控制器......

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

知道为什么吗? 我需要配置什么吗?

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

Martin Devillers提出了一个解决方案:ASP.NET MVC 4 RC:让WebApi和区域很好地发挥作用

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

将其更改为:

    // 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

完美工作。

最新更新