2015-09-28 61 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} 
      ); 
    } 
}