2015-09-28 58 views
0

我想添加一個正確的路由到我的Asp.net MVC網站。ASP.NET MVC URL路由與單路徑地圖

  • www.example.com/profile/39(資料/ {ID}):其用於示出一些一項的輪廓。
  • www.example.com/profile/edit(資料/編輯):其用於編輯當前用戶配置文件

,這裏是我的路線:

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


     routes.MapRoute("ShowProfile", 
      "Profile/{id}", 
     new { controller = "Profile", action = "Index" }); 


     routes.MapRoute(
      name:"Profile", 
      url: "{controller}/{action}" 
      ); 



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

是我的問題,當我先將ShowProfile路線正確顯示配置文件,但是當我輸入www.example.com/profile/edit時,它顯示缺少Int值的錯誤,並且在首先將Profile路線放入www.example.com/profile/39時顯示404錯誤。
我試圖用改變我的途徑來解決這個問題:這種格式

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

      routes.MapRoute("EditProfile", 
      "Profile/Edit", 
      new { controller = "Profile", action = "Edit" }); 

      routes.MapRoute("ShowProfile", 
     "Profile/{id}", 
    new { controller = "Profile", action = "Index" }); 

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

它工作正常兩種情況,但它顯示了一個404錯誤像其他發佈方式:

[HttpPost] 
    [ValidateAntiForgeryToken] 
     public ActionResult EditEmail() 
    { 

      return RedirectToAction("Index","Home"); 

    } 

但我不想爲我的所有方法添加路由值,有沒有一種通用的方式來不添加逐個路由值?

回答

0

您需要檢查您的控制器。可能它們確實不包含返回HTTP404的這些操作。

這種方法很適合我和所有的URL作品:

  • 本地主機:24934 /資料/ 5
  • 本地主機:24934 /型材/編輯
  • 本地主機:24934 /家
  • 本地主機:24934 /家用/主
  • 本地主機:24934 /家用/主/ 7

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult Main() 
    { 
     return View(); 
    } 
}  
public class ProfileController : Controller 
{ 
    public ActionResult Edit() 
    { 
     return View(); 
    } 

    public ActionResult Show(int id) 
    { 
     @ViewBag.id = id; 
     return View(); 
    } 
} 

路線:

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

     routes.MapRoute("EditProfile", 
      "Profile/Edit", 
      new {controller = "Profile", action = "Edit"}); 

     routes.MapRoute("ShowProfile", 
      "Profile/{id}", 
      new {controller = "Profile", action = "Show"}); 

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