【问题标题】:How is URL Routing handled when the URLs are 3+ levels deep? (RESTful URLs)当 URL 深度超过 3 级时,如何处理 URL 路由? (RESTful URL)
【发布时间】:2015-07-08 18:09:15
【问题描述】:

假设您需要在 RESTful 路由中包含这些 URL:

/Company/About

/Company/Product/View
/Company/Product/Edit

/Company/Contact/View
/Company/Contact/Edit

我假设所有这些操作都需要在同一个控制器(即公司)中,并且我还假设路由在 Global.asax 中看起来像这样:

public static void RegisterRoutes(RouteCollection routes)
{
     routes.MapRoute("mission", "Company/Product/{action}/{id}",
          new { controller = "Company", id = "" });

     routes.MapRoute("mission", "Company/Contract/{action}/{id}",
          new { controller = "Company", id = "" });

     routes.MapRoute(
          "Default",                                              
          "{controller}/{action}/{id}",                           
          new { controller = "Home", action = "Index", id = "" } 
     );
}

当试图将所有这些都塞进一个控制器时就会出现问题(而且,我再次假设将所有这些都放在同一个控制器中是正确的),因为控制器动作名称会搞砸一切。这就是我的意思:

在本例中,我们需要在 Company 控制器中命名如下控制器操作:

About (for Company/About)

ProductView (for /Company/Product/View)
ProductEdit (for /Company/Product/Edit)

ContactView (for /Company/Contact/View)
ContactEdit (for /Company/Contact/Edit)

但是,这些操作名称与路由表所期望的不匹配。例如,如果用户浏览到 /Company/Product/View,则路由将直接流向 Company 控制器中名为“View”的操作。如果用户浏览到 /Company/Contact/View 怎么办?路由会将流路由到公司控制器中的相同“视图”表。如何将这些请求路由到不同的视图?

你会如何解决这个问题?我的目标是尽可能的 RESTful。

【问题讨论】:

  • /Company/Contact/Edit 通常会建议您使用名为 AreaCompany

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

首先要成为 RESTful,您不应该在路由名称中包含操作。您应该通过 http 动词进行路由,而不是在路由中指定编辑或查看。我还建议使用属性路由

这是一个示例控制器:

[RoutePrefix("api/company")]
public class CompanyController : ApiController
{
    [Route("product"), HttpGet]
    public Product ViewProduct()
    {
    }

    [Route("product"), HttpPut]
    public Product EditProduct()
    {
    }

    [Route("contact"), HttpGet]
    public Product ViewContact()
    {
    }

    [Route("contact"), HttpPut]
    public Product EditContact()
    {
    }
}

【讨论】:

  • 你究竟是如何在 ASP.NET MVC 中做到这一点的呢?我的意思是,如果您在路由中设置了 /{controller}/{action},则必须始终将操作名称放入 URL。例如,您不能只执行 /Contract/12483(这是 RESTful 方式)来查看合同,因为路由需要 ID 所在的操作名称。这是真正的 RESTful 方式,但不能在 ASP.NET MVC 中完成,因为需要在 URL 中包含操作名称。
  • 我提出的方法是使用属性路由。所以你可以做 [Route("contract/{id}")] 然后将 id 添加到方法参数中。使用属性路由,您不再需要遵循 /{controller}/{action} 约定的路由方式。此链接可能对asp.net/web-api/overview/web-api-routing-and-actions/… 有所帮助
猜你喜欢
  • 1970-01-01
  • 2019-04-24
  • 2012-06-11
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 2011-07-02
  • 1970-01-01
相关资源
最近更新 更多