MVC3 and Rewrites

本文关键字:Rewrites and MVC3 | 更新日期: 2023-09-27 17:57:31

我正在编写一个MVC3应用程序,该应用程序需要使用http://[server]/[City]-[State]/[some-term]/形式的URL重写。

据我所知,MVC3包含一个路由引擎,该引擎使用Global.asax文件中定义的{controler}/{action}/{id}:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

传统上(在非MVC应用程序中),我会使用一些URL重写风格来解码URL,例如http://www.myserver.com/City-State/somesearch/要查询如下所示的字符串参数:http://www.myserver.com/city=City&state=状态&query=somesearch

请记住,此请求将来自http://www.myserver.com/Home

这可以在不必指定控制器的情况下实现吗。。。像这样的东西:

routes.MapRoute(
            "Results",
            "{city}-{state}/{searchTerm}",
            new { controller = "Results", action = "Search" }
        );

还是最好把控制器列出来?

您如何在MVC3环境中处理此问题?

谢谢。

MVC3 and Rewrites

asp.net MVC3中的URL重写:-您可以在Global.asax文件中编写url重写代码:-

       //Default url
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            "Default",
            "", 
            new { controller = "Home", action = "Index", id = "" }
        );
      //others url rewriting you want
        RouteTable.Routes.MapRoute(null, "Search/{City_State}/{ID}", new { controller = "Home", action = "Search" });

看看这两个答案:

  • ASP.NET MVC路由:如何定义自定义路由
  • 在ASP.Net MVC中定义自定义URL路由

摘要:

  • 在默认路由之前指定自定义路由
  • 在常规之前定义特定路线,因为它们可能与两者相匹配
  • 默认值是可选的
  • 在默认参数对象中指定默认的控制器和操作

您可以通过在Global.asax文件中注册路由来实现这一点,但要注册路由很重要,您必须先注册旧路由,然后再注册新路由。

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// for Old url 
routes.MapRoute(
    "Results",
    "{city}-{state}/{searchTerm}",
    new { controller = "Results", action = "Search" }
);
// For Default Url 
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);