同时使用AttributeRoutes和MapRoute作为区域

时间:2015-08-13 19:06:37

标签: asp.net-mvc routing asp.net-mvc-routing asp.net-mvc-areas

所以我在我的MVC应用程序中有不同的区域,我想使用属性和其他一些MapRoute定义一些路由:

这是什么是RouteConfig文件:

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

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Dashboard_route",
        url: "Dashboard/{action}",
        defaults: new {controller = "Dashboard", action = "Index"}
    );
}

当我使用属性([RouteArea("someRoute")][Route])时,一切都很好,但是当涉及MapRoute时,控制器找不到区域目录下的我的视图文件夹而且我是收到此错误: 未找到视图'getdashboard'或其主控或没有视图引擎支持

the searched locations. The following locations were searched:
~/Views/Dashboard/getdashboard.aspx
~/Views/Dashboard/getdashboard.ascx
~/Views/Shared/getdashboard.aspx
~/Views/Shared/getdashboard.ascx
~/Views/Dashboard/getdashboard.cshtml
~/Views/Dashboard/getdashboard.vbhtml
~/Views/Shared/getdashboard.cshtml
~/Views/Shared/getdashboard.vbhtml

无论如何使用MapRoute定义Views目录?

1 个答案:

答案 0 :(得分:0)

通常,在创建区域时,AreaRegistration目录中有一个/Areas/<Area Name>/类,用于注册其路径。

public class TestAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Test";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Test_default",
            "Test/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

然后从您的Application_Start()方法中,您需要确保致电AreaRegistration.RegisterAllAreas(),以便执行此注册码。

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();
    }
}

一旦设置完成,它就会在/Areas/<Area Name>/Views/目录中查找视图。