Micael
Micael

Reputation: 6970

Data lookup in route constraints?

Is it a recommended practice to do data lookup in route constraints, or should they be kept lightweight?

I would like to have a route constraint that triggers a 404 if a user tries to access a product that does not exist - i.e.:

/en-US/products/myproductcode

But I'm concerned about the performance implications, even if the lookup is trivial.

Thanks

Upvotes: 0

Views: 124

Answers (1)

Çağdaş Tekin
Çağdaş Tekin

Reputation: 16661

Well, it doesn't sound like a good solution to me, even though the performance wouldn't matter much (you'll connect to your DB in the controller to get the product anyway).

Even if a product code doesn't exist in your DB, it doesn't mean the URL doesn't match your route.

For example, NerdDinner 1.0 handles your situation like this :

public ActionResult Details(int id) { 
    Dinner dinner = dinnerRepository.GetDinner(id);
    if (dinner == null) {
        //Here, you can make sure the response status code is 404
        return View("NotFound");
    }
    return View(dinner);
}

Upvotes: 1

Related Questions