Search code examples
asp.net-mvc-2aopcross-cutting-concerns

asp.net MVC 2 - most elegant way of isolating guard code - guarding against null controller parameters


I have a very simple problem, but I'm looking for the 'best' solution to the following:

I have multiple controller actions something like this:

public ActionResult DoSomething(PackageViewModel packageByName, DoSomethingInputModel inputModel)
{
    if (packageByName == null)
    {
        Response.StatusCode = 404;
        Response.StatusDescription = "Package not found : " + RouteData.GetRequiredString("packageName");
        return View("Error");
    }
    ...

What is the best way to isolate this cross cutting concern?

  • I can make a function
  • I can use an AOP tool like PostSharp
  • ActionFilter
  • Other?

Solution

  • In fact ActionFilter is an AOP. Write your own ActionFilter implementation to chceck if parameter is not null. If you always need to check the same thing on the beggining of your controller execution then it's the best way. It's easy to write, resusable in whole application and very MVC 2.