Removing boilerplate from ASP.NET MVC actions
asp.net, asp.net-mvc, c#
Solution
As others have suggested you could write filters or invoke an AOP framework like PostSharp.
However, that might be a tall order for some. You might want to consider writing something simple, maintainable and fairly readable, that everyone on the team can immediately understand:
public ActionResult Show(int object_id)
{
SomeClass obj = Require<SomeClass>(object_id, assumption: o => o.SomeCheck);
// processing
}
//Perhaps: put this in a base controller or other common class
private object Require<T>(int id, Func<object, bool> assumption) where T : class
{
var o = ObjectRepository.ById(object_id) as T;
//Result is required
if (o == null) {
throw new HttpException(404);
}
//Verify assumption
if (!assumption(o)) {
throw new HttpException(403);
}
return o;
}
Problem
I have something like this in almost every action: ``` public ActionResult Show(int object_id) { Object obj = ObjectRepository.ById(object_id); if (obj == null) { throw new HttpException(404); } if (obj.SomeCheck) { throw new HttpException(403); } // processing } ``` Question is how to move object getting (and throwing http exceptions) away from action and have something like this: ``` public ActionResult Show(Object obj) { // processing } ``` UPD: Can't change ObjectRepository and model itself, it's used not only with ASP.NET but in other parts of the project.