【发布时间】:2012-08-27 16:48:02
【问题描述】:
我有一个包含两个模型的 Web 项目 - IndicatorModel 和 GranteeModel。我也有相应的 ApiControllers - IndicatorsController 和 GranteesController。我计划将此设置用于数据 API 以及我的实际 Web 项目,因此我在我的项目中创建了一个名为“Api”的新区域。在我的ApiAreaRegistration 类中,我正在为这些控制器注册路由,如下所示:
context.Routes.MapHttpRoute(
name: "ApiDefault",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
基本上,对http://myapp/api/indicators/123 的请求应该发送到指标控制器,并且它应该由一个接受整数参数的操作方法专门处理。我的控制器类设置如下,并且运行良好:
public class IndicatorsController : ApiController
{
// get: /api/indicators/{id}
public IndicatorModel Get(int id)
{
Indicator indicator = ...// find indicator by id
if (indicator == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return new IndicatorModel(indicator);
}
}
我的GranteesController 课程设置相同:
public class GranteesController : ApiController
{
// get: /api/grantees/{id}
public GranteeModel Get(int granteeId)
{
Grantee grantee = ... // find grantee by Id
if (grantee == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return new GranteeModel(grantee);
}
}
现在的问题 - 如果我尝试向 http://myapp/api/grantees/123 发出请求,我会收到 404,并且我 100% 肯定 404 不是来自我的 Get 方法。一方面,我尝试过在该方法中调试和记录,但该方法实际上从未被命中。此外,请求的实际输出 (json) 如下所示:
{
"Message": "No HTTP resource was found that matches the request URI 'http://myapp/api/grantees/25'.",
"MessageDetail": "No action was found on the controller 'Grantees' that matches the request."
}
此外,我的 TraceWriter 日志的输出如下所示:
;;http://myapp/api/grantees/10
DefaultHttpControllerSelector;SelectController;Route='controller:grantees,id:10'
DefaultHttpControllerSelector;SelectController;Grantees
HttpControllerDescriptor;CreateController;
DefaultHttpControllerActivator;Create;
DefaultHttpControllerActivator;Create;MyApp.Areas.Api.Controllers.GranteesController
HttpControllerDescriptor;CreateController;MyApp.Areas.Api.Controllers.GranteesController
GranteesController;ExecuteAsync;
ApiControllerActionSelector;SelectAction;
DefaultContentNegotiator;Negotiate;Type='HttpError', formatters=[JsonMediaTypeFormatterTracer...
所以我的请求被正确路由 - 选择了正确的控制器,并且 Id 属性设置正确 (10)。但是,ApiControllerActionSelector 没有在控制器上找到匹配的方法。我还尝试在我的 Get 方法中添加 [HttpGet] 属性,但没有成功。
有人对这里可能发生的事情有任何想法吗?我一生都无法弄清楚为什么动作选择器没有找到正确的动作。
【问题讨论】:
-
仅供参考 - 这是 MVC 4 附带的 ASP.NET Web API。
-
哦,是的 - 对不起,应该包括那个。我正在为所有 WebApi 内容使用 4.0.20710.0 版本,据我所知,这是最新的稳定版本。
标签: asp.net-mvc-routing asp.net-web-api