简体   繁体   中英

ASP.NET MVC attribute routing not hitting correct controller

I have a couple of controllers like this:

[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();
    }
}

But I cannot seem to get to my index action in the side navigation controller - if I browse to localhost/side-navigation/test it's hitting the catch all controller with side-navigation/test as it's pathname instead of the side navigation one with test as the pathname.

Can anyone see anything I am doing wrong here or how to make the side navigation controller work?

This is the route config:

// MVC attribute routing
routes.MapMvcAttributeRoutes();

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

Weirdly, if I change the route of the side navigation index to test/{pathname} and browse to side-navigation/test/test it will work and the controller will be hit but I don't want to add anything before the pathname

似乎您没有使用[Area],也在上面的方法中放置了[Route(“ [action]”))属性。

Ok I have fixed this by adding an asterisk before the pathname:

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

If anyone can explain why this works and without an asterisk doesn't, it would be greatly appreciated, as I also have a product controller set up in exactly the same way that doesn't need the asterisk

[RoutePrefix(“ side-navigation”)]公共类SideNavigationController:BaseController {[Route(“ {* pathname}”)] public ActionResult Index(string pathname){}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM