2013-03-15 39 views
1

我有一個API控制器:怎麼寫圖路線mvc4

public class ExchangesController : ApiController 
{ 
    [HttpGet] 
    public List<ExchangesTrade> GetTrades(long tid) 
    { 

我希望能夠從瀏覽器中調用它像/api/USD/trades.json?tid=5

我應該怎麼寫「routes.MapRoute」在我RouteConfig?

回答

1

首先,routes.MapRoute會爲傳統的MVC應用添加路由,如果你想爲你的web api添加路由,你需要在你的web api HttpConfiguration路由上使用MapHttpRoute添加Http路由。

在Web API的配置,你可以添加一個URI路徑映射擴展這樣的:

config.Formatters 
     .JsonFormatter 
     .MediaTypeMappings 
     .Add(new UriPathExtensionMapping("json", "application/json")); 

添加這樣的路線:

config.Routes.MapHttpRoute(
     name: "ExchangesRouteWithExtensions", 
     routeTemplate: "api/USD/{action}.{ext}/{tid}", 
     defaults: new { controller = Exchanges, tid = RouteParameter.Optional } 
    ); 

然後訪問您的端點是這樣的:

api/USD/trades.json?tid=5