NullReferenceException in ASP.NET MVC 5: Fix “Object Reference Not Set”

Quick answer. Check the lookup result before reading its properties. Return HTTP 404 when the requested order is missing. Use a fallback only for a customer name your view explicitly treats as optional.

ASP.NET MVC 5 · NullReferenceExceptionOrder details actionOrder NumberCheck lookupRender or return 404
Order Number → Check lookup → Render or return 404

What throws this error?

System.NullReferenceException
Object reference not set to an instance of an object.

A customer opens an order URL after the order has been deleted. Your repository returns null and the controller reads order.Number before Razor renders anything.

The action examples use ASP.NET MVC 5 on .NET Framework 4.8 with C# 7.3 syntax. Run them in a local MVC 5 project with the corresponding view and the synthetic inputs described below. The C# exception semantics also apply to ASP.NET Core. In a Core controller, adapt MVC 5 result helpers and service lifetimes to Core’s APIs.

How to reproduce and fix it

Put the broken fragment in the relevant action or helper in a local test project. Use the failing case from the verification table. If your project already has a try/catch or error filter, turn on break-on-throw in Visual Studio to stop at the failure before that handler runs.

Reproduce the error · C#
var order = repository.Find(id);
return View(new OrderViewModel { Number = order.Number });

Set a breakpoint on the failing action. In Visual Studio, open Debug → Windows → Exception Settings and enable breaking when System.NullReferenceException is thrown. Request an ID that exists and one that was deleted. If your log only points to a compound expression such as order.Customer.Name, split it into locals and inspect each reference.

Corrected code · C#
var order = repository.Find(id);
if (order == null) return HttpNotFound();
return View(new OrderViewModel {
    Number = order.Number,
    CustomerName = order.Customer?.Name ?? "Guest"
});

Inspect order and order.Customer separately at the first thrown exception. If the response reaches Razor, inspect the view's @model declaration and the View(model) call. If a constructor-injected repository is null, correct container wiring or guard the constructor with ArgumentNullException.

How can I verify the fix?

Run all three cases. Check the response or displayed result and confirm the failing case now follows the intended application path.

Test inputExpected result
Existing order with customer200 and customer name
Existing guest order200 and Guest
Missing order404

The table describes expected behavior for the sample inputs. Runtime execution was not verified in an MVC 5 environment.

Prevent the same failure in production

Decide which values are required before adding null guards. An absent record is a normal lookup result and maps to 404. A missing repository or connection dependency is an application fault and should surface in logs. If a customer is optional only for guest checkout, validate the domain rule so real account-data problems stay visible.

Keep a regression case for the condition that triggered the error. When production logging is useful, record the operation and a correlation identifier. Keep raw request data, stack traces, and configuration secrets out of public error responses.

Frequently asked question

Should I put ?. on every property?

Use it when the preceding value is genuinely optional. For a required relationship, preserve the invariant or report the data problem explicitly.

Microsoft Learn reference

Comments