尝试使用AttributeRouting创建默认的ASP.NET MVC路由

时间:2012-02-19 05:11:52

标签: c# .net asp.net-mvc routes attributerouting

我刚开始在我的ASP.NET MVC3应用程序中使用AttributeRouting。我开始使用-no-控制器。 (新空MVC3应用程序)

然后我做了一个区域。 (称为:Documentation

然后我添加了一个控制器(名为:DocumentationController

我已经这样做了..

[RouteArea("Documentation")]
public class DocumentationController : Controller
{
    [GET("Index")]
    public ActionResult Index()
    {
        return View();
    }
}

以下路线有效:/documentation/index

但是我怎样才能使这两条路线起作用?

1 - /< - (默认路线/未指定特定路线) 2 - 添加了/documentation< - no'index'子路由部分。

可以使用AttributeRouting完成吗?

更新

我知道如何使用默认的ASP.NET MVC3结构等来做这件事。我想要做的是通过AttributeRouting来解决这个问题。

1 个答案:

答案 0 :(得分:9)

我假设您希望将“/”和“/ documentation”映射到DocumentationController.Index,是吗?如果是这样,请执行以下操作:

[RouteArea("Documentation")]
public class DocumentationController : Controller
{
    [GET("Index", Order = 1)] // will handle "/documentation/index"
    [GET("")] // will handle "/documentation"
    [GET("", IsAbsoluteUrl = true)] // will handle "/"
    public ActionResult Index()
    {
        return View();
    }
}

一点解释:

  • GET(“Index”)具有Order = 1,以将其标记为操作的主要路径。由于反射如何工作,因此无法在不使用Order属性的情况下确定操作的属性顺序。 See here
  • 您可以将多个获取路由映射到单个操作。 See here
  • IsAbsoluteUrl属性允许您覆盖RouteArea和RoutePrefix属性添加的URL前缀。这样最终路由将匹配根请求。 See here

希望这会有所帮助。如果我对您尝试做的事情的初步假设不正确,请发表评论。