.net 处理请求时发生未处理的异常

wnavrhmk  于 2022-12-27  发布在  .NET
关注(0)|答案(1)|浏览(165)

我如何修复此错误
处理请求时发生未处理的异常。AmbiguousMatchException:请求与多个终结点匹配。匹配项:
核心演示.区域.管理.控制器.主控制器.索引(核心演示)核心演示.控制器.主控制器.索引(核心演示)
命名空间核心演示.控制器{公共类家庭控制器:控制器{私有只读ILogger _logger;

public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
    public IActionResult Test()
    {
        return View();
    }
}

}

/////////////////////////////////////////////////////////////////////////////////////

namespace CoreDemo.Areas.Admin.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}
fnvucqvd

fnvucqvd1#

问题是,您注册到同名的控制器(HomeController),而没有定义自定义路由,那么.net不知道选择哪个。
您可以使用Route属性为控制器提供自定义路径请参阅此处的文档:https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-7.0#attribute-routing-with-http-verb-attributes
因此,您可以将Route属性添加到代码中,如下所示:

namespace CoreDemo.Areas.Admin.Controllers
{
    [Route("admin/[controller]/[action]")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return ControllerContext.MyDisplayRouteInfo();
        }
    }
}

namespace CoreDemo.Controllers 
{ 
    [Route("[controller]/[action]")]
    public class HomeController : Controller 
    { 
        private readonly ILogger _logger;
    
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
    
        public IActionResult Index()
        {
            return View();
        }
    
        public IActionResult Privacy()
        {
            return View();
        }
    
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public IActionResult Test()
        {
            return View();
        }
    }
}

相关问题