ASP.NET Core 路由引擎混乱

Jef*_*eff 5 c# asp.net-core

我正在尝试创建一个关于 ASP.NET Core 路由引擎如何工作的可靠示例,结果让我感到惊讶。

此示例背后的前提是点击控制器索引页面,然后使用 AJAX 请求加载数据。

我用 MVC 创建了一个 ASP.Net Core 应用程序。然后我添加了以下控制器:

namespace WebApplication2.Controllers {
    using Microsoft.AspNetCore.Mvc;

    public class SearchController : Controller {
        public IActionResult Index() {
            return View();
        }

        [HttpGet("{company}")]
        public IActionResult Get(string company) {
            return Ok($"company: {company}");
        }

        [HttpGet("{country}/{program}")]
        public IActionResult Get(string country, string program) {
            return Ok($"country: {country} program: {program}");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我还创建了一个简单的视图,与带有“搜索页面”字样的索引一起使用,以便您可以看到它被调用。

问题是由此创建的路由没有意义。

预期成绩

  • /搜索/索引
  • /搜索/{公司}
  • /搜索/{国家}/{程序}

以公司:“ABC”,国家:“加拿大”和程序:“管道”为例:

  • /搜索/索引

    产生:“搜索页面”

  • /搜索/美国广播公司

    制作“公司:ABC”

  • /搜索/加拿大/水暖

    产生:“国家:加拿大计划:管道”

实际结果

然而,它根本不是这样工作的。相反,这些是结果:

  • /搜索/索引

产生:“国家:搜索程序:索引”

  • /搜索/美国广播公司

产生:“国家:搜索程序:ABC”

  • /搜索/加拿大/水暖

产生:404 未找到

很明显,Index 和 Get string company 的路由混淆了,它将 Controller 名称视为参数。

我可以使用以下代码使其工作,但我认为路由引擎会产生相同的结果:

    public class SearchController : Controller {
        public IActionResult Index() {
            return View();
        }

        [HttpGet("[controller]/{company}")]
        public IActionResult Get(string company) {
            return Ok($"company: {company}");
        }

        [HttpGet("[controller]/{country}/{program}")]
        public IActionResult Get(string country, string program) {
            return Ok($"country: {country} program: {program}");
        }
Run Code Online (Sandbox Code Playgroud)

我的理解有什么问题?必须[controller]明确指定似乎很愚蠢。

Rya*_*yan 3

您已经混合了常规路由和属性路由,但您不应该这样做。

/Search对于您的原始代码,当您删除网址中的所有内容时,它将起作用。

要使用控制器名称,您需要[Route("[controller]")]在 mvc 控制器上进行设置,以使您的 url 按预期工作。

[Route("[controller]")]
public class SearchController : Controller
{
    [HttpGet("[action]")]
    public IActionResult Index()
    {
        return View();
    }

    [HttpGet("{company}")]
    public IActionResult Get(string company)
    {
        return Ok($"company: {company}");
    }

    [HttpGet("{country}/{program}")]
    public IActionResult Get(string country, string program)
    {
        return Ok($"country: {country} program: {program}");
    }
}
Run Code Online (Sandbox Code Playgroud)