2016-03-04 67 views
0

我正在爲我的MVC應用程序寫幾條路線。我有我的應用程序以下途徑:由於我爲控制器的特定操作編寫了路由,是否需要爲控制器內的所有操作編寫路由?

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

以上時使用我想訪問喜歡的默認值路徑:

www.servicili.com/budget/edit/1

www.servicili.com/professional/view/234

但是,我創建了以下路線爲特定目的:

routes.MapRoute(
       name: "Perfil", 
       url: "{UsuApelido}", 
       defaults: new { controller = "Perfil", action = "Index"} 
      ); 

以上,用於訪問一個「水暖工」例如的URL輪廓的路線: www.servicili.com/MarkZuckberg

輪廓細節是控制器上PERFIL和行動索引,但是,因爲我寫了這條路線,所有其他行動不起作用。

例如:如果我試圖訪問另一個控制器內指數行動,將其重定向到的指數 PERFIL

- 問題是:由於我爲控制器的特定操作編寫了路由,是否需要爲控制器內的所有操作編寫路由?在2號位

routes.MapRoute(
      name: "Perfil", 
      url: "{*UsuApelido}", 
      defaults: new { controller = "Perfil", action = "Index"}, 
      constraints: new { UsuApelido = new PlumberUrlConstraint() } 
     ); 

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

回答

2

解決你的問題試試這樣,

首先定義約束,

public class PlumberUrlConstraint: IRouteConstraint 
{ 
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     var db = new YourDbContext(); 
     if (values[parameterName] != null) 
     { 
     var UsuApelido = values[parameterName].ToString(); 
     return db.Plumbers.Any(p => p.Name == UsuApelido); 
     } 
     return false; 
    } 
} 

定義兩條路線,把 「默認」 路線現在,如果你有'Perfil'控制器中的'索引'動作,你可以像這樣得到水管工的名字,

public ActionResult Index(string UsuApelido) 
{ 
    //load the content from db with UsuApelido 
    //display the content with view 
} 

希望得到這個幫助。

+0

只需要修復代碼並在Constring的最後添加} new:您知道一個鏈接以獲取有關如何在MVC中學習創建路由的更多參考? tks非常多 – Dan

+0

你可以試試[這個鏈接](http://www.asp.net/mvc/overview/controllers-and-routing) –