2013-10-31 67 views
2

大師,MVC定製路由與驗證

在我的項目中,我指定了許多不同的路線,如下所示。

routes.MapRoute(
    name: "StudentMerit", 
    url: "Student-Merit", 
    defaults: new { controller = "StudentMerit", action = "GetData"}); 

routes.MapRoute(
    name: "StudentResults", 
    url: "Student-Results", 
    defaults: new { controller = "StudentResults", action = "GetData"}); 

正如你所看到的網址是連字符分開,我不是動作名稱

所有這些途徑可以改寫太多擔心,如果我可以告訴MVC,在 URL替換連字符什麼也沒有,它會做我的控制者。

喜歡的東西,

routes.MapRoute(
    name: "AllInOne", 
    url: "{Cont-roller}", 
    defaults: new { controller = {Cont-roller}.replace("-",""), action = "GetData"}); 

有沒有辦法做到這一點? 請幫忙。

在此先感謝。

回答

4

創建您自己的RouteHandler。我不知道這是否是最好的解決方案。

public class RemoveDashRouteHandler : MvcRouteHandler 
{ 
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext) 
    { 
     requestContext.RouteData.Values["controller"] = ((string)requestContext.RouteData.Values["controller"]).Replace("-", String.Empty); 

     return base.GetHttpHandler(requestContext); 
    } 
} 

使用

routes.MapRoute(
    name: "AllInOne", 
    url: "{controller}", 
    defaults: new { controller = "Default", action = "GetData" } 
).RouteHandler = new RemoveDashRouteHandler(); 

編輯的替代解決方案

我發現子類路線則覆​​蓋GetRouteData一個更好的解決方案(在我看來)。由於Route的職責是生成RouteData,而MvcRouteHandler的責任是獲取IHttpHandler,所以更好。

public class RemoveDashRoute : Route 
{ 
    private const string ControllerKey = "controller"; 

    public RemoveDashRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints = null, RouteValueDictionary dataTokens = null, IRouteHandler routeHandler = null) 
     : base(url, defaults, constraints ?? new RouteValueDictionary(), dataTokens ?? new RouteValueDictionary(), routeHandler ?? new MvcRouteHandler()) 
    { 
    } 
    public override RouteData GetRouteData(HttpContextBase httpContext) 
    { 
     var routeData = base.GetRouteData(httpContext); 
     if (routeData != null && routeData.Values.ContainsKey(ControllerKey)) 
     { 
      routeData.Values[ControllerKey] = ((string)routeData.Values[ControllerKey]).Replace("-", String.Empty); 
     } 
     return routeData; 
    } 
} 

使用

routes.Add("AllInOne", new RemoveDashRoute(
    url: "{controller}", 
    defaults: new RouteValueDictionary(new { controller = "Home", action = "GetData" })) 
); 
+0

你可能是指'RemoveDashRouteHandler'。 – haim770

+0

哦,快點。你是對的 – LostInComputer

+0

是的..第二選擇似乎更好! –