2012-07-14 216 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