2017-06-05 99 views
1

我在理解Web API 2如何處理路由時遇到一些問題。.Net Web API與路徑不匹配

  • 我創建了一個PostsController是工作在標準的動作,GETPOST方面就好了,等
  • 我想補充一點,是PUT動作稱爲Save()採用一個模型作爲自定義路由一個論點。
  • 我在自定義路線前添加了[HttpPut][Route("save")]。我也修改了WebAPIConfig.cs來處理模式api/{controller}/{id}/{action}
  • 但是,如果我在郵遞員中使用http://localhost:58385/api/posts/2/save(使用PUT),我會收到沿着No action was found on the controller 'Posts' that matches the name 'save'的錯誤消息。本質上是一個美化404.
  • 如果我改變路線爲[Route("{id}/save")]由此產生的錯誤依然存在。

我在做什麼不正確?

WebAPIConfig.cs

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

PostController.cs

// GET: api/Posts 
public IHttpActionResult Get() 
{ 
    PostsStore store = new PostsStore(); 
    var AsyncResult = store.GetPosts(); 
    return Ok(AsyncResult); 
} 

// GET: api/Posts/5 
public IHttpActionResult Get(string slug) 
{ 
    PostsStore store = new PostsStore(); 
    var AsyncResult = store.GetBySlug(slug); 
    return Ok(AsyncResult); 
} 

// POST: api/Posts 
public IHttpActionResult Post(Post post) 
{ 
    PostsStore store = new PostsStore(); 
    ResponseResult AsyncResult = store.Create(post); 
    return Ok(AsyncResult); 
} 

    // PUT: api/Posts/5 DELETED to make sure I wasn't hitting some sort of precedent issue. 
    //public IHttpActionResult Put(Post post) 
    // { 

     //  return Ok(); 
    //} 

[HttpPut] 
[Route("save")] 
public IHttpActionResult Save(Post post) 
{ 
    PostsStore store = new PostsStore(); 
    ResponseResult AsyncResponse = store.Save(post); 
    return Ok(AsyncResponse); 
} 
+1

使用'RouteDebugger' NuGet包,它會告訴你到底是什麼路線路由引擎正在尋找,它是在哪裏尋找,找到匹配的路由,爲什麼它不能找到它。路由引擎不能用幾個字來描述。有很多可以說。 – CodingYoshi

回答

2

如果使用[Route]屬性然後就是屬性路由作爲並列到您配置的基於約定的路由。您還需要啓用屬性路由。

//WebAPIConfig.cs 

// enable attribute routing 
config.MapHttpAttributeRoutes(); 

//...add other convention-based routes 

而且還必須正確設置路線模板。

//PostController.cs 

[HttpPut] 
[Route("api/posts/{id}/save")] // Matches PUT api/posts/2/save 
public IHttpActionResult Save(int id, [FromBody]Post post) { 
    PostsStore store = new PostsStore(); 
    ResponseResult AsyncResponse = store.Save(post); 
    return Ok(AsyncResponse);  
} 

參考Attribute Routing in ASP.NET Web API 2

+0

屬性路由已經啓用,但正如您的答案中所述,我沒有以api開頭的完整路徑。 –