【问题标题】:ASP.NET MVC 4: One controller routing is not like the othersASP.NET MVC 4:一个控制器路由与其他控制器路由不同
【发布时间】:2013-03-05 22:45:03
【问题描述】:

我已将一个新控制器“LoggingController”添加到已具有多个控制器的 MVC 4 应用程序中。 现在我注意到这个控制器的路由行为与已经存在的不同。

例如,下面两个url按预期正常工作,并点击了BlogController中的“Index”方法。

http://localhost:56933/Blog/

http://localhost:56933/Blog/Index

除了我添加的控制器之外的所有其他控制器也是如此:

http://localhost:56933/Logging/Index - 正常工作,点击 LoggingController 中的“Index”方法

http://localhost:56933/Logging/ - 返回“'/' 应用程序中的服务器错误。找不到资源。”

除了显而易见的事情之外,我应该从哪里开始寻找?

这是来自 LoggingController 的索引签名

public ActionResult Index(int? page, string Period, string LoggerProviderName, string LogLevel, int? PageSize)

MapRoute 中没有特定于某个控制器的内容。以下是完整的 RouteConfig 供参考:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    routes.MapRoute(
    name: "Display",
    url: "Post/{id}/{seofriendly}",
    defaults: new { controller = "Post", action = "Display", id = UrlParameter.Optional, seofriendly = ""}
        );

    routes.MapRoute(
        name: "SEOFriendly",
        url: "{controller}/{action}/{id}/{seofriendly}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, seofriendly = "" }
    );

    routes.MapRoute(
        name: "SEOFriendlyNoId",
        url: "{controller}/{action}/{seofriendly}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, seofriendly = "" }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

【问题讨论】:

    标签: asp.net-mvc-4 routing controller


    【解决方案1】:

    您的 Index 方法实际上没有与您的任何可用路由匹配的签名。您必须为您的索引操作提供默认值,或者在路由表的开头添加额外的路由以指定这些默认值。例如:

    routes.MapRoute(
        name: "LoggingDefaults",
        url: "Logging/{Period}/{LoggerProviderName}/{LogLevel}/{page}/{PageSize}",
        defaults: new {controller = "Logging", 
                       action = "Index",
                       page = UrlParameter.Optional,
                       PageSize = UrlParameter.Optional,
                       LoggerProviderName = "SomeProvider",
                       Period = "SomePeriod",
                       LogLevel = "SomeLevel"}
    

    【讨论】:

    • 我明白了!我选择了默认值。奇怪的是,当我刚刚修改 Index 方法时,这还不够。当我删除并重新创建控制器 + 索引时,它开始按预期工作。无论如何,现在一切都很好。
    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多