If you are using ASP.NET MVC, Core or non-Core, chances are you are swallowing NullReferenceException without you even noticing.

You can see the screenshot of this repro in my previous post (see: Sixth, fixed null model)

But, let’s reproduce this using simple ASP.NET MVC Core program.

First, just create a normal MVC application. Then, add the following action:

public IActionResult Sample()

{

return View();

}



Also, add this new ModelView class.

public class PantsViewModel

{

public string FancyPants { get; set; }

}

Yeah, fancy pants ala Scott Hanselman. I’m a huge fan of his!!

He is amazing! Also, check this out:

Oh, back to the topic…

Add a new View using Visual Studio dialog, use “Create” as Template, and then choose our newly created SampleViewModel as the Model class, like this:

Add MVC View

The result should be like this:

Our generated View file

Nothing special here.

It’s just an ordinary View, without those shared layout applied, just for the sake of simplicity. Now press F5 and try to access the page.

View result

There is no exception. Of course.

Now turn on this setting in Visual Studio:

Enable capturing NullReferenceException

and also this one:

Disable ‘Just My Code’

Now, try to access the page again.