在 ASP.NET MVC 中,RouteConfig 类负责配置应用程序的路由规则。默认情况下,该类的代码位于 Global.asax.cs 文件中的 Application_Start 方法中。然而,有时候在某些情况下,RouteConfig 的改动可能不会立即生效,这可能会导致路由规则不正确的问题。下面是一种解决方法,可以在 ASP.NET MVC 中解决“RouteConfig - 改动检测较晚”的问题。
using System.Web.Mvc;
using System.Web.Routing;
public class AppRouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
// 在这里配置路由规则
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
using System.Web.Mvc;
using System.Web.Routing;
protected void Application_Start()
{
// 注册新的路由配置类
AppRouteConfig.RegisterRoutes(RouteTable.Routes);
}
通过以上步骤,我们将默认的 RouteConfig 类替换为了一个新的类,并在 Global.asax.cs 文件中调用新的路由配置类的方法来注册路由规则。这样做的好处是,我们可以确保在应用程序启动时就加载新的路由规则,避免了默认的 RouteConfig 类在改动时检测较晚的问题。