我的路線:路由問題:找到了多個動作匹配請求
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: null,
constraints: new { id = @"^\d+$" }
);
routes.MapHttpRoute(
name: "ApiControllerActionRoute",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我的方法:
// GET api/Set/All
[ActionName("All")]
public IEnumerable<Set> GetSets()
{
var sets = _repository.GetAllSets();
return sets;
}
// GET api/Set/TopLevelSets
[ActionName("TopLevelSets")]
public IEnumerable<Set> GetTopLevelSets()
{
var sets = _repository.GetTopLevelSets();
return sets.ToList();
}
// GET api/Set/Breadcrumbs/1
[ActionName("Breadcrumbs")]
public IEnumerable<Set> GetBreadCrumbs(int id)
{
var sets = _repository.GetBreadcrumbs(id);
return sets.ToList();
}
// GET api/Set/5
public Set GetSet(int id)
{
Set set = _repository.GetSet(id);
if (set == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return set;
}
// PUT api/Set/5
public HttpResponseMessage PutSet(Set set)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
_repository.UpdateSet(set);
return Request.CreateResponse(HttpStatusCode.OK);
}
// POST api/Set
public HttpResponseMessage PostSet(Set set)
{
if (ModelState.IsValid)
{
_repository.AddSet(set);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, set);
return response;
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
// DELETE api/Set/5
public HttpResponseMessage DeleteSet(int id)
{
_repository.DeleteSet(id);
return Request.CreateResponse(HttpStatusCode.OK, id);
}
在這一點上,我試圖打本地主機/ API /套/ 1 - getSet方法。一切似乎都與路線一致,但由於某種原因,它不起作用。我錯過了什麼?
這是僞代碼還是剪切粘貼?您的GetSet操作缺少ActionName註釋:[ActionName(「Set」)],因此GetSet與您正在查找的Set路徑不匹配 – 2013-03-04 03:39:49
剪切並粘貼 - 是否會觸及第一條路線並說controller = Set和id = 1?在添加非標準方法和第二次路由註冊之前,這是工作的。如果我添加Action註解,那麼我不需要點擊/ api/set/set/1? – RobVious 2013-03-04 03:45:28
否 - 動作名稱屬性實際上會將名稱GetSet替換爲所需的名稱「Set」。通過使用[ActionName(「Set」)],它將具有Route/api(controller)/ set(action)/ 1(id) - 匹配您的GetSet操作。或者,您可以將您的操作從GetSet重命名爲Set(這可能會更容易理解) – 2013-03-04 03:59:49