Cacomania: ASP.NET MVC 4: Show a 404 page if the model is null

Cacomania

ASP.NET MVC 4: Show a 404 page if the model is null

Guido Krömer - 17. February 2013 - Tags: , ,

The ASP.NET MVC Attributes are mighty and can be used for automating different tasks. One of this task I ran into is display the view if the model was found or display a 404 page if not.

As example look at the pseudo code below, instead of writing this kind of code block again and again in many different actions:

public ActionResult Show(int id)
{
    //load my model

    if (model == null) 
    {
        //redirect to 404
    }
    //display view
}

Using an attribute could automate this and lead to lesser code, look at the pseudo code one liner below:

[OnModelEmpty404]
public ActionResult Show(int id)
{
    //load my model and display view
}

ActionFilterAttribute

All I needed is a new ActionFilterAttribute which checks if the model is null after the action was executed. The attribute just looks for a ViewResult, appending the attribute to an action which returns a RedirectToRouteResult for example will lead to a 404, too.

If the model is null a new HttpException gets thrown.

using System.Web;
using System.Web.Mvc;

namespace AspMVC404
{
    public class OnModelEmpty404Attribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ViewResult viewResult = filterContext.Result as ViewResult;


            if (viewResult.Model == null) 
            {
                throw new HttpException(404, "Not found");
            }
        }
    }
}

The example/test controller

The example controller has just one action which displays the typed view if the request is not /Test/Show/1337 and lead into a 404 if the id equals 1337

using System.Web.Mvc;

namespace AspMVC404.Controllers
{
    public class TestController : Controller
    {
        [OnModelEmpty404]
        public ActionResult Show(int id)
        {
            if (id == 1337)
            {
                return View("Show", null);
            }

            return View(new FakeModel {
                Foo = id,
                Bar = "Bar"
            });
        }
    }
}

Here is the result tested with Firebug:
ASP .NET MVC4 no 404 because of model != null.
The model has been found.
Just the 404, produced by the attribute, in Firebug.
No model was found.

That's All Folks! I hope you enjoyed my tiny post.