gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:33:45 27 4
gpt4 key购买 nike

我刚刚开始使用 AttributeRouting使用我的 ASP.NET MVC3 应用程序。我一开始根本没有 Controller 。 (新的空 MVC3 应用程序)

然后我做了一个区域。 (称为:文档)

然后我添加了一个 Controller (称为:DocumentationController)

然后我就这样做了..

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

以下路线有效:/documentation/index

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

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

这可以用 AttributeRouting 来完成吗? ?

更新:

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

最佳答案

我假设您希望“/”和“/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

希望这对您有所帮助。如果我对您尝试执行的操作的初步假设不正确,请发表评论。

关于c# - 尝试使用 AttributeRouting 创建默认的 ASP.NET MVC 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9346926/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com