gpt4 book ai didi

asp.net-mvc-routing - 获取请求正确解析了我的 Controller ,但没有调用正确的(或任何)操作

转载 作者:行者123 更新时间:2023-12-01 16:30:16 26 4
gpt4 key购买 nike

我有一个包含两个模型的 Web 项目 - IndicatorModelGranteeModel。我还有对应的 ApiControllers - IndicatorsControllerGranteesController。我计划将此设置用于数据 API 以及我的实际 Web 项目,因此我在我的项目中创建了一个名为“Api”的新区域。在我的 ApiAreaRegistration 类中,我正在为这些 Controller 注册路由,如下所示:

context.Routes.MapHttpRoute(
name: "ApiDefault",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

基本上,对 http://myapp/api/indicators/123 的请求应该转到 Indicators Controller ,并且应该由接受整数参数的操作方法专门处理。我的 Controller 类设置如下,并且运行良好:

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 是 不是 来 self 的 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...

所以我的请求被正确路由 - 选择了正确的 Controller ,并且 Id 属性设置正确 (10)。但是,ApiControllerActionSelector 在 Controller 上找不到匹配的方法。我还尝试将 [HttpGet] 属性添加到我的 Get 方法中,但没有成功。

有人知道这里会发生什么吗?我一辈子都弄不明白为什么 Action 选择器找不到正确的 Action 。

最佳答案

GranteesController 的 action 上的参数名称需要从 'granteeId' 修改为 'id':

public GranteeModel Get(int id)

关于asp.net-mvc-routing - 获取请求正确解析了我的 Controller ,但没有调用正确的(或任何)操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12146109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com