'Visual Studio 22 Scaffolding MVC Controller With View & Entity Framework Not Aware of Areas

I have created a new .Net Core project using Visual Studio 22. Inside of my project I have created a new area (it was created successfully and works as expected).

Upon creating a new scaffolded item, all of the assets (controller & views) are created, however the code generated in my views is not aware of area they were created in.

For example my structure is /Areas/Admin/Flags

I can hit /Admin/Flags/Index just fine.

However, all of the links and form actions point to /Flags/[Action]

It's as if the scaffolding engine was not aware that I was creating these assets inside of an area.

Any ideas?



Solution 1:[1]

Make sure app.UseEndpoints with area in the pattern is an early middleware extension in /program.cs. I added right below app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
      name: "areas",
      pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
    );
});

It will automatically utilize the area in the route.

Also, don't forget to copy _ViewImports.cshtml into the root of the /areas/[area]/Views folder, else links won't be clickable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob