I'm trying to create a http://www.domain.com/product
route. It should look in the database for the product name and, if found, calls a controller and, if not, follows to the next route.
I've tried to create the route bellow, but I could not figure how to follow to the next routes in case {shortcut}
product name is not found in the database.
routes.MapRoute(
name: "easyshortcut",
url: "{shortcut}",
defaults: new { controller = "Home", action = "Product" }
);
Thanks
You can do this via a route constraint:
routes.MapRoute(
name: "easyshortcut",
url: "{shortcut}",
defaults: new { controller = "Home", action = "Product" },
constraints: new { name = new ProductMustExistConstraint() }
);
Where name
is your parameter name in the Product action of the HomeController
.
Then implement the constraint:
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;
}
}
(The above was adjusted to this situation from this answer .)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.