【问题标题】:asp.net MVC default action not working in areaasp.net MVC 默认操作在区域中不起作用
【发布时间】:2018-04-29 08:55:09
【问题描述】:

我有一个项目,其中声明了一个设置区域和一个 URL,只要我明确包含“/Index”操作即可。问题是当我使用 RedirectToAction("Index") 时,它会从 URL 中排除“/Index”并且我得到一个 404 Page Not Found。网址是:

http://localhost:40078/Setup/Facility/Index - 有效
http://localhost:40078/Setup/Facility/ - 404(带或不带尾随 /)

路由配置:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapMvcAttributeRoutes();

        AreaRegistration.RegisterAllAreas();

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "T.C.MVCWeb.Controllers" }
        );
    }

设置区域注册:

public class SetupAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Setup";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Setup_default",
            "Setup/{controller}/{action}/{id}",
            defaults: new { action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "T.C.MVCWeb.Areas.Setup.Controllers" }
        );
    }
}

请求的控制器

namespace T.C.MVCWeb.Areas.Setup.Controllers
{
    public class FacilityController : Controller
    {
        // GET: FacilitySetup
        public ActionResult Index()
        {
            ...
        }
    }
}

我添加了 Phil Haack 的 RouteDebugger,可以看到 404 请求认为“设置”是控制器,但我不明白为什么,其余的输出让我感到困惑而不是帮助。

【问题讨论】:

  • 很可能有一个属性路由在之前您的区域路由与/Setup/Facility/ 匹配。这可能是配置中的属性路由或其他区域路由。如果您将 routes.MapMvcAttributeRoutes() 注释为测试,是否匹配?
  • 好电话,你是对的。我的一位开发人员出于某种原因设置了大量的属性路由。有问题的是Setup/{action},它旨在允许区域URL本身http://localhost:40078/Setup/映射到SetupController。我认为唯一的选择是为那里的每个动作硬编码一条路线,对吗?例如。 Setup/Index 默认为 Setup 控制器和 Index 操作?之后,两个 URL 都可以工作。让我失望的是 RouteDebugger 没有突出显示 Setup/{action} 与我的设施 URL 匹配。它仅在列表顶部显示“n/a”作为匹配项。谢谢!
  • 要么使用具有恒定段的 URL,要么使用路由约束以确保它们与您打算用于 \Setup 区域的路由不匹配。虽然,您的主要问题似乎是站点的 2 个不同部分名为 Setup - 将所有这些部分移至 Setup 区域可能更易于维护。
  • 没有两个不同的部分。 SetupController 位于Setup 区域。我们只希望该区域本身的 URL 托管该区域的登录页面。我想这可以指定为Setup_default 的默认控制器和动作,但他试图让它也有一个动态的{action}

标签: asp.net-mvc-5 url-routing asp.net-mvc-routing


【解决方案1】:

感谢 NightOwn888 的评论,我找到了通过属性声明的路线。有问题的路由属性声明了 Setup/{action},旨在允许区域 URL 本身 http://localhost:40078/Setup/ 映射到 SetupController。

【讨论】:

    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 2017-06-03
    • 2019-05-12
    • 2011-09-22
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多