【问题标题】:ASP.NET MVC attribute routing not hitting correct controllerASP.NET MVC 属性路由未命中正确的控制器
【发布时间】:2019-04-30 10:07:42
【问题描述】:

我有几个这样的控制器:

[RoutePrefix("side-navigation")]
public class SideNavigationController : BaseController
{
    [Route("{pathname}")]
    public ActionResult Index(string pathname)
    {
        SideNavigationPopoutModel model = _sideNavFactory.Value.CreatePopout(pathname);

        if (model != null)
        {
            return View(model);
        }

        return HttpNotFound();
    }
}

public class CatchAllController : BaseController
{
    public ActionResult Index(string pathname)
    {
        CatchAllModel model = _catchAllModelFactory.Value.Create(pathname);

        if (model != null)
        {
            // TODO: Do we need this - what does it do?
            // TempData.Restore(this);

            return View(model);
        }

        return HttpNotFound();
    }
}

但我似乎无法在侧面导航控制器中执行索引操作 - 如果我浏览到 localhost/side-navigation/test,它会使用 side-navigation/test 击中所有控制器,因为它是路径名,而不是带有 test 的侧面导航控制器路径名。

谁能看到我在这里做错了什么或如何使侧面导航控制器工作?

这是路由配置:

// MVC attribute routing
routes.MapMvcAttributeRoutes();

// Default catch all route
routes.MapRoute(
    "Default",
    "{*pathname}",
    new { controller = "CatchAll", action = "Index" });

奇怪的是,如果我将侧边导航索引的路径更改为 test/{pathname} 并浏览到 side-navigation/test/test 它将起作用并且控制器将被击中,但我不想在路径名之前添加任何内容

【问题讨论】:

  • 试试这个:routes.MapRoute( "Default", "{controller}/{id}", new { controller = "CatchAll", action = "Index", id = "" });
  • 对不起,这不是只允许在 url 上使用 id 参数并将其默认为空字符串吗?不知道这将如何解决路由问题,无论如何试一试,它只是打破了包罗万象的路由
  • 抱歉搞错了..你可以试试这个:routes.MapRoute( "Default", "{controller}/{id}", new { controller = "CatchAll", action = "Index", id = UrlParameter.Optional });

标签: c# asp.net-mvc routes asp.net-mvc-5.2


【解决方案1】:

看来你没有使用 [Area] 也把属性 [Route("[action]")] 放在方法上面。

【讨论】:

  • 不幸的是,这不起作用,我不想在 url 结构中添加区域(这就是我不使用区域属性的原因)
【解决方案2】:

好的,我已通过在路径名前添加星号来解决此问题:

[RoutePrefix("side-navigation")]
public class SideNavigationController : BaseController
{
    [Route("{*pathname}")]
    public ActionResult Index(string pathname)
    {
    }
}

如果有人能解释为什么这行得通而没有星号则不行,将不胜感激,因为我也有一个产品控制器,其设置方式与不需要星号的方式完全相同

【讨论】:

    【解决方案3】:

    [RoutePrefix("side-navigation")] 公共类 SideNavigationController : BaseController { [路线(“{*路径名}”)] 公共 ActionResult 索引(字符串路径名) { } }

    【讨论】:

    • 你能解释一下为什么这应该是一个解决方案吗?
    • 您似乎只是从我的答案中复制了代码,但没有格式化或解释它为什么应该工作,所以不确定这是添加了什么
    猜你喜欢
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多