我正在尝试将ASP.NET Web API(来自MVC 4)添加到我的项目中......但是我在从Area / WebAPI / Controller获得任何响应时遇到了一些麻烦(不太确定在哪里它出错了......)
我安装了Route Debugger,如果我转到我的主页面......我看到路线......
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
任何想法为什么?我需要配置什么吗?
答案 0 :(得分: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
答案 1 :(得分: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
完美无缺。