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

Pur*_*ome 5 .net c# 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

以下路线,有效: /documentation/index

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

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

可以使用AttributeRouting完成吗?

更新:

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

spo*_*pot 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

一点解释:

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

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