【问题标题】:ASP.NET MVC3 routing REST services to controllerASP.NET MVC3 将 REST 服务路由到控制器
【发布时间】:2012-03-02 23:00:31
【问题描述】:

我想通过以下方式路由 REST 服务 url:

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

    无论您在哪里注册路由,通常在 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() { }
    

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      相关资源
      最近更新 更多