I am starting to switch over my Controllers to use model binders for GET actions instead of using an int parameter. My normal controller GET action looks like the following …
public ActionResult Details(int id)
{
DomainModel model = repository.GetById(id);
if (model == null)
{
throw new HttpException(404, "Item does not exist")
}
//Continue along with our controller action
}
When switch to a ModelBinder I wanted to throw the HttpException in the BindModel method, however I am unsure if it is considered a good programming practice. Is the controller responsiblity for throwing the 404 or the ModelBinder?
Model binding does just that, binds the model. if the model doesn’t exist it would return either null or a Null Object. The controller could then decide what to do with the model. If it’s null, throw.
however if you you see the same lines of code appearing than it’s a good idea to encapsulate that code. One option would be to use an ActionFilter. the model binder creates the objects and the action filter can set the response code to 404 if the model is null.
in this scenario your controller only needs to worry about the “happy path”. That is the model exists.