ASP.NET MVC3将REST服务路由到控制器

时间:2011-05-03 11:44:00

标签: c# asp.net asp.net-mvc-3 url-routing

我想以下列方式路由REST服务URL:

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

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

所以基本上我在网址中为Rest做了一个硬编码的例外。

我对MVC路由不太熟悉。那么实现这一目标的好方法是什么?

1 个答案:

答案 0 :(得分:16)

无论您在何处注册路线,通常都在global.asax

        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() { }