MVC 3区域路由不起作用

Mar*_*rco 11 c# asp.net-mvc c#-4.0 asp.net-mvc-3

我在我的MVC 3应用程序中创建了一个名为"Blog"的区域.

在global.asax中,我有以下代码.

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

    }
Run Code Online (Sandbox Code Playgroud)

这是我所在地区的代码

public class BlogAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get { return "Blog"; }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Blog_default",
            "Blog/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

当我转到以下URL http:// localhost/CMS/blog时,我收到以下错误.

未找到视图"索引"或其主数据或视图引擎不支持搜索的位置.搜索了以下位置:〜/ Views/blog/Index.aspx~/Views/blog/Index.ascx~/Views/Shared/Index.aspx~/Views/Shared/Index.ascx~/Views/blog/Index. cshtml~/Views/blog/Index.vbhtml~/Views/Shared/Index.cshtml~/Views/Shared/Index.vbhtml

我该如何解决这个问题?

Min*_*ive 26

我找到了我认为是框架中的错误,并找到了解决方法.如果您尝试将默认路由映射到带有区域的MVC 3应用程序,则global.asax文件可能具有以下内容:

VB:

routes.MapRoute(
      "Default",
      "{area}/{controller}/{action}/{id}",
      New With {.area = "MyArea", .controller = "Home", .action = "Index", .id = UrlParameter.Optional}
)
Run Code Online (Sandbox Code Playgroud)

C#:

routes.MapRoute(
       "Default",
       "{area}/{controller}/{action}/{id}",
       new { area = "MyArea", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

如果您转到URL中的应用程序根目录,则可能会出现如下运行时错误:

未找到视图"索引"或其主数据或视图引擎不支持搜索的位置.搜索了以下位置:

出于某种原因,视图引擎似乎不会在视图文件的区域文件夹中查找与键入整个链接相同的内容.奇怪的是代码到达控制器动作.以下是修复:将此代码放在您的控制器操作中:

VB:

If Not Me.ControllerContext.RouteData.DataTokens.ContainsKey("area") Then
                Me.ControllerContext.RouteData.DataTokens.Add("area", "MyArea")
            End If
Run Code Online (Sandbox Code Playgroud)

C#

  if (!this.ControllerContext.RouteData.DataTokens.ContainsKey("area"))
{
        this.ControllerContext.RouteData.DataTokens.Add("area", "MyArea")
 }
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 8

您所在地区的注册似乎是错误的.您为操作指定了默认值,但没有为控制器指定默认值.由于您通常将Home作为控制器的名称,因此您需要指定它.

也可能是您没有正确设置文件夹,因为您应该进行物理设置:

  • /地区/博客
  • /地区/博客/控制器
  • /地区/博客/浏览次数

...一旦您修复了博客区域路线,您还需要:

  • / Areas/Blog/Views/Home <<将索引视图放在此处

你得到的错误似乎很清楚地表明这是问题所在.