2012-07-14 169 views
0

海兰网址重写MVC

我写了下面的代码

public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
     routes.MapRoute(
      "Home", // Route name 
      "", // URL with parameters 
      new { controller = "Home", action = "Index" } // Parameter defaults 
     ); 
     routes.MapRoute(
        "Controller_Action", // Route name 
        "{controller}/{action}/{id}", // URL with parameters 
        new { id = UrlParameter.Optional } // Parameter defaults 
     ); 
     foreach (var route in GetDefaultRoutes()) 
     { 
      routes.Add(route); 
     } 
     routes.MapRoute(
      "UserPage", // Route name 
      "{id}", // URL with parameters 
      new { controller = "Home", action = "Get" } // Parameter defaults 
     ); 
    } 




    private static IEnumerable<Route> GetDefaultRoutes() 
    { 
     //My controllers assembly (can be get also by name) 
     Assembly assembly = typeof(test1.Controllers.HomeController).Assembly; 
     // get all the controllers that are public and not abstract 
     var types = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Controller)) && t.IsPublic && !t.IsAbstract); 
     // run for each controller type 
     foreach (var type in types) 
     { 

      //Get the controller name - each controller should end with the word Controller 
      string controller = type.Name.Substring(0, type.Name.IndexOf("Controller")); 
      // create the default 
      RouteValueDictionary routeDictionary = new RouteValueDictionary 
               { 
                {"controller", controller}, // the controller name 
                {"action", "index"} // the default method 
               }; 
      yield return new Route(controller, routeDictionary, new MvcRouteHandler()); 
     } 
    } 

我是新来的MVC,我要重写我的网址财产以后这样的,假设我的网址是像www.myhouse.com /产品/索引/ 1然后我想只显示www.myhouse.com/prduct-name为更好的SEO性能,我使用mvc4测试版,我也有一个通过URL Rewriting in .Net MVC,但它不适合我....

但我不知道如何将传递值传递给此方法。

+0

为什么使用“mvc”(与语言无关的设计模式的名称)来描述ASP.NET MVC 4框架?你是谁的人之一,在桌面上“interent”也称IE图标? – 2012-07-14 13:04:33

+0

这是不是在桌面上的“interent”调用IE图标,在mvc这可能我不知道这就是为什么我问你... – jats 2012-07-14 19:24:09

+0

你可以使用URL重写(属性重写),请检查链接我已给出 http://sreerejith.blogspot.in/2015/07/url-rewriting-in-mvc-4-attribute-routing.html – 2015-07-28 09:00:33

回答

2

经过大量在互联网上搜索,我得到了我的解决方案

添加以下代码global.asax

routes.MapRoute(
      "Home", // Route name 
      "", // URL with parameters 
      new { controller = "Home", action = "Index" } // Parameter defaults 
     ); 
     routes.MapRoute(
      "jats", // Route name 
      "{jats}", // URL with parameters 
      new { controller = "Home", action = "Content" } // Parameter defaults 
     ); 

然后在下面的代码添加到视图:

@Html.ActionLink("test", "Content", new { jats= "test-test" }) 

下面的代码添加到HomeController

public ActionResult Content(string jats) 
{ 
    return View(); 
} 

然后您完成了......现在URL与您在查询字符串中传递相同...因此您的控制器名称和查询字符串参数将不会显示。

+0

参数如何? – JoshYates1980 2016-03-24 15:31:27