【发布时间】:2016-12-02 18:52:03
【问题描述】:
我已经阅读了这些问题:
Multiple actions were found that match the request: webapi
Web API Routing - multiple actions were found that match the request Multiple actions were found that match the request Web API?
我已经更新了我的 RouteConfig 如下:
routes.MapRoute(
name: "Receipt",
url: "api/{controller}/{action}/{id}",
defaults: new { controller = "Receipt", action = "Post", source = UrlParameter.Optional }
);
创建这个新的路线图丝毫没有帮助解决问题
以下是Controller中的相关函数:
public HttpResponseMessage Post ([FromBody]CreateReceiptViewModel source)
{
try
{
// stuff happens here
}
catch (Exception ex)
{
// something went wrong, save exception data to the database
// RecordError(ex, "Post Receipt", "ReceiptController/Post");
}
}
//public void RecordError(Exception ex, string action = "", string origin = "PocketPlooto API")
//{
// Error Error = new Error
// {
// Date = DateTime.Now,
// Detail = ex.ToString(),
// Message = ex.Message,
// Origin = origin,
// StackTrace = ex.StackTrace,
// Action = action
// };
// db.Errors.Add(Error);
// db.SaveChanges();
//}
这个函数相当大,所以我觉得在这里包含是不切实际的。
有趣的是,虽然RecordError 被评论了,但帖子却很好。
如果我取消注释,则会出现错误(我的测试环境不允许我以 JSON 以外的格式查看它,给您带来的不便深表歉意):
"Message":"发生错误。",
"ExceptionMessage":"找到与请求匹配的多个操作:\r\nPost on type WebApiService.Controllers.ReceiptController\r\nRecordError on type WebApiService.Controllers.ReceiptController",
"ExceptionType":"System.InvalidOperationException",
"StackTrace":" 在 System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n 在 System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n 在系统。 Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancelToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
不幸的是,我并不真正了解堆栈跟踪,而且由于这里显然没有任何重复的操作,我什至无法开始猜测 Web Api 正在做什么,或者为什么控制器中出现此问题是一个问题。
谁能清楚说明堆栈跟踪的含义以及为什么额外的功能会出现问题?
【问题讨论】:
-
为什么不使用路由属性?我怀疑它会将您的方法 Post 和 RecordError 映射到同一个 URL
-
这真的很奇怪,因为 RecordError 应该只是一个内部方法。客户永远不应该知道它的存在。可能是因为我错误地将 RecordError 设为公共方法?
-
然后尝试将其设为私有
-
你的控制器里只有这2个方法吗?
-
不,还有其他一些。都是私人的。显然,将函数设为私有会取消它们作为路由候选者的资格,因此将
RecordError方法设为私有似乎已经解决了问题
标签: c# asp.net-web-api