c# - routes.MapMvcAttributeRoutes() 和 context.Routes.MapMvcAttributeRoutes() 有什么区别?

标签 c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

我有一个 mvc 应用程序,其中包含名为 account 的附加区域

我正在使用 MvcSiteMapProvider 制作面包屑

我有一个返回特定发票详细信息的操作。此操作的 url 类似于 localhost/account/profile/invs-histr/details/ID,其中 ID 是要显示的发票 ID。

我有 accountAreaRegistration.cs 用于注册区域路由,我有 RouteConfig.cs 用于注册全局路由。

目前,我必须在两个文件中为 localhost/account/profile/invs-histr/details/ID 注册路由。如果我没有在 accountAreaRegistration.cs 中注册此路由,我将遇到 404 异常。如果我不在 RouteConfig.cs 中注册此路由,则不会呈现面包屑。

RouteConfig.cs 文件开头:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapMvcAttributeRoutes();
}

accountAreaRegistration.cs:

public override void RegisterArea(AreaRegistrationContext context)
{
   context.Routes.MapMvcAttributeRoutes();
}

谁能给我解释一下,routes.MapMvcAttributeRoutes()context.Routes.MapMvcAttributeRoutes() 有什么区别?

为什么我应该在两个文件中注册路由?

提前致谢

最佳答案

这是一个扩展方法,因此您调用它的对象是第一个参数。这个参数是一个RouteCollection,这个集合在这两种情况下是不同的:

  • 在第一次调用中注册了具有路由属性的应用程序“根目录”中的 Controller 路由
  • 在第二次调用中,对当前区域内的 Controller 执行相同的操作

如果你想避免对每个区域进行第二次调用,你可以用 [RouteArea("AreaName")] 属性装饰你的 Controller 。

如果您想更好地了解属性路由,请参阅此文档:Attribute Routing in ASP.NET MVC 5请特别注意区域部分。

关于c# - routes.MapMvcAttributeRoutes() 和 context.Routes.MapMvcAttributeRoutes() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27483606/

相关文章:

c# - 在两个参数之间切换值 [最佳实践/更好的代码]

c# - Razor 中枚举下拉列表的显示名称

javascript - Razor 在 javascript 中查看 if/else 语句

c# - WCF 无法解析 Java Soap 响应

c# - 如何找到正在检测 EventSystem.current.IsPointerOverGameObject 的对象?

c# - 检查两个列表中相同的元素

asp.net-mvc - 我的 HtmlHelper 有什么问题?

asp.net - 接收 OData.PageResult<T> 时如何避免 406?

ajax - MVC 4 Ajax.BeginForm POST 未绑定(bind)到 Controller 中的模型

asp.net-mvc - 我应该在 ASP.NET MVC 4 中使用 AsyncController 吗?