如何创建 www.domain.com/product MVC 路由

How to create www.domain.com/product MVC route

我正在尝试创建一条 http://www.domain.com/product 路线。 它应该在数据库中查找产品名称,如果找到,则调用控制器,如果没有,则遵循下一条路线。

我尝试创建下面的路线,但我不知道如何在数据库中找不到 {shortcut} 产品名称的情况下进行下一条路线。

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

谢谢

您可以通过路由约束来做到这一点:

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

其中 name 是您在 HomeController 的 Product 操作中的参数名称。

然后实现约束:

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;

    }
}

(以上是从这个answer调整到这种情况的。)