views:

27

answers:

2

Hi all 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?
+2  A: 

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.

ŁukaszW.pl
(tick) If anyone is struggling with he implementation details see my answer also.
Myster
A: 

Here's what I implemented (based on @ŁukaszW.pl answer)
Hopefully this will save someone some time.

public class GuardAgainstNullPackage : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        BookingController controller = ((BookingController)filterContext.Controller);
        if (filterContext.ActionParameters["packageByName"] == null || !(filterContext.ActionParameters["packageByName"] is PackageViewModel))
        {
            controller.Response.StatusCode = 404;
            controller.Response.StatusDescription = "Package not found : " + filterContext.RouteData.GetRequiredString("packageName");
            filterContext.Result = new ViewResult() { ViewName = "Error" };
        }
        base.OnActionExecuting(filterContext);
    }
}
Myster