您可以通過路由約束做到這一點:
routes.MapRoute(
name: "easyshortcut",
url: "{shortcut}",
defaults: new { controller = "Home", action = "Product" },
constraints: new { name = new ProductMustExistConstraint() }
);
凡name
在HomeController
的產品你的動作參數名。
然後實現約束:(以上調整,從這個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;
}
}