Clarice Bouwer
Clarice Bouwer

Reputation: 3811

NullReferenceException when I try to add a new ApiController in .NET Core

I see this error message:

NullReferenceException on add of empty ApiController

When I try to scaffold a controller for and empty API Controller by following these steps:

Right-click on folder

> Add

> Controller...

> Add Scaffold -> API Controller - Empty

> Click Add

Specifications:

---Edit---

I can't replicate the problem now. One of the suggestions given by @chriss-pratt must have worked (Thank You!) While doing a tutorial, I came across the section to add scaffold tooling and perform initial migration. In case you experience this and the below doesn't work, this part of the tutorial my be promising (if you decide to stick with scaffolding that is).

Upvotes: 0

Views: 402

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239440

ASP.NET Core doesn't strictly have an ApiController class. ASP.NET Core doesn't have separate MVC and Web Api components. Everything is just Controller. ApiController is available through a separate "shim" NuGet package, but that's only to make migrating old ASP.NET Web Api code easier. You shouldn't be using it for any new development.

That said, the problem you're having here is with the scaffold. It might be due to the fact that you're trying to scaffold ApiController rather than just Controller. You haven't give any information about what version of Visual Studio you're using or what version of ASP.NET Core.

Try the simple stuff like closing and restarting Visual Studio. If it persists, you can try repairing Visual Studio. Hit the windows key and begin typing "Visual Studio Installer". Open that when it shows up. Below your installed copy of Visual Studio in the list, there will be a drop down menu that looks like three dots stacked on top of each other. There's an option there to "Repair". Start the process and go grab a cup of coffee. It essentially reinstalls Visual Studio, so it'll likely take a while.

All that said, honestly, your best bet is to just don't worry about it. Scaffolding is all but useless anyways. Especially with ASP.NET Core, all you get is a class, which you can easily create yourself. A controller is merely a class that inherits from Controller. Add a new class in your Controllers directory, name it WhateverController and then add : Controller after the name in the code. Then, just start adding your actions and such as normal.

Upvotes: 2

Related Questions