自定义RouteBase中的View未被区域拾取

时间:2015-03-18 11:58:57

标签: c# asp.net-mvc asp.net-mvc-5

我有一个自定义RouteBaseMyRoute我想为区域"MyArea"工作,其中包含以下代码:

public override GetRouteData(HttpContextBase httpContext)
{
    var result = new RouteData(this, new MvcRouteHandler());

    result.Values.Add("area", "MyArea");
    result.Values.Add("controller", "MyController");
    result.Values.Add("action", "Index");
}

我在MyAreaAreaRegistration.cs文件中注册了这个:

public override string AreaName { get { return "MyArea"; } }

public override void RegisterArea(AreaRegistrationContext context)
{
    context.Routes.Add(new MyRoute());

    // other routes
    context.MapRoute(/* ... */);
}

在发出请求时,它成功调用Index上的MyController操作:

public ActionResult Index()
{
    return this.View();
}

但是,MVC没有在视图的正确文件夹中搜索:

  

视图'索引'或者找不到它的主人,或者没有视图引擎支持搜索到的位置。搜索了以下位置:
  〜/查看/ myController的/的Index.aspx
  〜/查看/ myController的/ Index.ascx
  〜/查看/共享/的Index.aspx
  〜/查看/共享/ Index.ascx
  〜/查看/ myController的/ Index.cshtml
  〜/查看/ myController的/ Index.vbhtml
  〜/查看/共享/ Index.cshtml
  〜/ Views / Shared / Index.vbhtml

当视图位于

~/Areas/MyArea/Views/MyController/Index.cshtml

如何在正确的区域进行MVC搜索?

1 个答案:

答案 0 :(得分:0)

如果您查看AreaRegistrationContext.MapRoute的来源,您会发现它将该区域与其他路线变量区别对待:

public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces)
{
    if (namespaces == null && this.Namespaces != null)
    {
        namespaces = this.Namespaces.ToArray<string>();
    }
    Route route = this.Routes.MapRoute(name, url, defaults, constraints, namespaces);
    route.DataTokens["area"] = this.AreaName; // *** HERE! ***
    bool flag = namespaces == null || namespaces.Length == 0;
    route.DataTokens["UseNamespaceFallback"] = flag;
    return route;
}

this.AreaName填充AreaRegistration

因此,问题的快速解决方法是更换呼叫:

result.Values.Add("area", "MyArea");

result.DataTokens["area"] = "MyArea";
相关问题