目次

Razor Pages アプリケーションで "An unhandled exception occurred while processing the request. AmbiguousMatchException: The request matched multiple endpoints. Matches:" エラーが発生する - ASP.NET Core

Razor Pages アプリケーションで "An unhandled exception occurred while processing the request. AmbiguousMatchException: The request matched multiple endpoints. Matches:" エラーが発生する現象について紹介します。

現象

Razor Pagesアプリケーションでページにアクセスすると以下のエラーが発生します。
An unhandled exception occurred while processing the request.
AmbiguousMatchException: The request matched multiple endpoints. Matches:

(ページ名1)
(ページ名2)
または
AmbiguousMatchException: The request matched multiple endpoints. Matches: (ページ名1) (ページ名2)


原因

複数のページが同じURLで衝突している可能性が高いです。

下記2つのRazor PageがWebアプリケーション内に存在している場合、どちらかのRazor Pageにアクセスするとエラーが発生します。
TestPage1.cshtml
@page "/TestPage"
@{
}
<html>
<head>

</head>
<body>
  <h2>TestPage1</h2>
  <p>テストページ1です。</p>
</body>
</html>
TestPage2.cshtml
@page "/TestPage"
@{
}
<html>
<head>

</head>
<body>
  <h2>TestPage2</h2>
  <p>テストページ2です。</p>
</body>
</html>

解説

TestPage1.cshtml と TestPage2.cshtml のページがありますが、@pageディレクティブではどちらも /TestPage が指定されています。 このためどちらのページも (アプリケーションルート/TestPage) でページが表示される動作となりページの衝突が起きてしまい、エラーが発生します。
この場合のエラーメッセージが以下となります。
AmbiguousMatchException: The request matched multiple endpoints. Matches: /TestPage1 /TestPage2

回避方法はそれぞれの@pageディレクティブが衝突しないよう別のパスを設定します。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2021-02-18
iPentec all rights reserverd.