2017-02-10 96 views
0

我有一個Web API,它在ASP.NET Core 1.1中使用基於約定的路由。我在我的Startup.csConfigure方法如下代碼:Web API不能使用基於約定的路由

app.UseMvc(routes => 
{ 
    routes.MapRoute(
     name: "api", 
     template: "api/inventory", 
     defaults: new { controller = "Inventory" }); 
}); 

我有一個包含另一個InventoryController.cs類:

public class InventoryController : Controller 
{ 
    [HttpGet] 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 
} 

我期望我會收到["value1","value2"]當我打電話api/inventory,但不是案子。我會收到一個404。我是ASP.NET新手,已經嘗試了幾乎所有我能想到的事情,並且很聰明。我會在這裏注意到,使用RouteAttribute可以使一切正常。

回答

0

你嘗試過做這樣

app.UseMvc(config => { 
      config.MapRoute(
       name: "Default", 
       template: "{controller}/{action}/{id?}" 
       ,defaults: new { controller="App", action="Index"} 
       ); 
     }); 

和你的類看起來像

[Route("api/Inventory")] 
public class InventoryController : Controller 
{ 
    [HttpGet] 
    public IEnumerable<string> Get() 
    { 
    return new string[] { "value1", "value2" }; 
    } 
} 
+0

正如我在我的問題提到的,使用'RouteAttribute'使一切工作正常。但我想知道爲什麼使用傳統路由不起作用。 – Hele