2011-05-03 114 views
5

我想通過以下方式路線REST服務網址:ASP.NET MVC3路由REST服務控制器

/User/Rest/ -> UserRestController.Index() 
/User/Rest/Get -> UserRestController.Get() 

/User/ -> UserController.Index() 
/User/Get -> UserController.Get() 

所以基本上我的網址進行硬編碼例外休息。

我對MVC路由不是很熟悉。那麼實現這個目標的好方法是什麼?

回答

16

無論您註冊的路線,常用於global.ascx

 routes.MapRoute(
      "post-object", 
      "{controller}", 
      new {controller = "Home", action = "post"}, 
      new {httpMethod = new HttpMethodConstraint("POST")} 
     ); 

     routes.MapRoute(
      "get-object", 
      "{controller}/{id}", 
      new { controller = "Home", action = "get"}, 
      new { httpMethod = new HttpMethodConstraint("GET")} 
      ); 

     routes.MapRoute(
      "put-object", 
      "{controller}/{id}", 
      new { controller = "Home", action = "put" }, 
      new { httpMethod = new HttpMethodConstraint("PUT")} 
      ); 

     routes.MapRoute(
      "delete-object", 
      "{controller}/{id}", 
      new { controller = "Home", action = "delete" }, 
      new { httpMethod = new HttpMethodConstraint("DELETE") } 
      ); 


     routes.MapRoute(
      "Default",       // Route name 
      "{controller}",  // URL with parameters 
      new { controller = "Home", action = "Index" } // Parameter defaults 
      ,new[] {"ToolWatch.Presentation.API.Controllers"} 
     ); 

在你的控制器

public ActionResult Get() { } 
public ActionResult Post() { } 
public ActionResult Put() { } 
public ActionResult Delete() { }