ASP.NET MVCアプリケーションで「!XXD3o!Multiple types were found that match the controller named 'Default'.」エラーが表示される現象について紹介します。
現象
ASP.NET WVCアプリケーションでビューのURLにアクセスると、下記のエラーメッセージが表示されます。
エラーメッセージ
!XXD3o!Multiple types were found that match the controller named 'Default'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.
The request for 'Default' has found the following matching controllers:
AspNetMvcArea.Controllers.DefaultController
AspNetMvcArea.Areas.Next.Controllers.DefaultController 表©鷗字㌍ 表©鷗字㌍ 表©鷗字㌍ 表©鷗字㌍ 表©鷗字㌍ 表©鷗字㌍ 表©鷗字㌍ !
原因
同じ名称のコントローラーが複数存在するため、どちらのコントローラーにアクセスしてよいか判断がつかないため、上記のエラーが発生します。
ソリューションエクスプローラでエラーが発生するプロジェクトのファイルを確認します。
今回エラーが発生したプロジェクトのファイル構成を確認すると、エリアが定義されていない部分とエリアが定義されている部分(MyArea部分)で同じ名前のコントローラーが使われていることがわかります。
この状態で、MyAreaの
MyArea/Default/Index
にアクセスするとView(ページ)が表示されます。
一方で エリア部分でないルート側の
Default/Index
にアクセスすると、
Multiple types were found that match the controller named 'Default'.」
のエラーが表示されます。ルートからは、ルートのDeafaultControllerもMyArea内のDefaultControllerも参照可能であるため、どちらのコントローラーを利用すればよいか決定できないためエラーが発生します。
対処法
ルートからは、ルートのDeafaultControllerもMyArea内のDefaultControllerも参照できるため、ルーティングの指定でネームスペースを指定することで解決できます。
RouteConfig.cs または Global.asax ファイルのルーティングの設定部分(MapRouteメソッド呼び出し部分)の引数を変更します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AspNetMvcAreaSameController
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
MapRouteのnamespaces 引数に
AspNetMvcAreaSameController.Controllers
を与えてエリア内の
AspNetMvcAreaSameController.Areas.MyArea.Controllers
がルーティングの対象でないことを明示的に指定します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AspNetMvcAreaSameController
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "AspNetMvcAreaSameController.Controllers" }
);
}
}
}
実行結果
MyAreaの
MyArea/Default/Index
にアクセスするとView(ページ)が表示されます。
ルートの
Default/Index
にアクセスした場合もエラーにならずView(ページ)が表示されます。
"Multiple types were found that match the controller named ..." エラーを解消することができました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2018-09-09
作成日: 2018-09-09