2015-04-19 29 views
0

我正在嘗試創建http://www.domain.com/product路線。 它應該在數據庫中查找產品名稱,如果找到,則調用控制器,如果沒有,則跟隨下一個路徑。如何創建www.domain.com/product MVC路線

我試圖創建路線波紋管,但是我無法知道如何在數據庫中找不到產品名稱的情況下跟隨到下一條路線{shortcut}

routes.MapRoute(
    name: "easyshortcut", 
    url: "{shortcut}", 
    defaults: new { controller = "Home", action = "Product" } 
); 

感謝

回答

2

您可以通過路由約束做到這一點:

routes.MapRoute(
    name: "easyshortcut", 
    url: "{shortcut}", 
    defaults: new { controller = "Home", action = "Product" }, 
    constraints: new { name = new ProductMustExistConstraint() } 
); 

nameHomeController的產品你的動作參數名。

然後實現約束:(以上調整,從這個answer這種情況)

public class ProductMustExistConstraint : IRouteConstraint 
{ 
    public bool Match(HttpContextBase httpContext, 
     Route route, 
     string parameterName, 
     RouteValueDictionary values, 
     RouteDirection routeDirection) 
    { 
     var productNameParam = values[parameterName]; 
     if (productNameParam != null) 
     { 
      var productName = productNameParam.ToString(); 

      /* Assuming you use Entity Framework and have a set of products 
      * (you can replace with your own logic to fetch the products from 
      * the database). 
      */ 

      return context.Products.Any(p => p.Name == productName); 
     } 

     return false; 

    } 
}