Multiple controller types were found that match the URL

当使用 Attribute 设置路由时,可能会出现一个 path 被两个 Controller 匹配结果,这样导致 MVC 不知道选用哪个 Controller 处理请求,例如:

[RoutePrefix("cms")]
public class CMSController : Controller
{
    [Route("{*path}")]
    public ActionResult Path(string path)
    {
        return Content("[Path]");
    }
}
[RoutePrefix("cms")]
public class FileController : Controller
{
    [Route("file")]
    public ActionResult File()
    {
        return Content("[File]");
    }
}

请求 /cms/file 时,返回错误信息如下:

Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

The request has found the following matching controller types:
dotnet_mvc_routing.Controllers.CMSController
dotnet_mvc_routing.Controllers.FileController

处理方法很简单,只要把两个 Controller 合并即可,例如:

[RoutePrefix("cms")]
public class CMSController : Controller
{
    [Route("{*path}")]
    public ActionResult Path(string path)
    {
        return Content("[Path]");
    }

    [Route("file")]
    public ActionResult File()
    {
        return Content("[File]");
    }
}

MVC 会优先匹配 /cms/file 的路由规则,再匹配 /cms/{*path} 的路由规则。

posted @ 2020-07-16 00:44  forhot2000  阅读(291)  评论(0)    收藏  举报