Eagle Eagle - 1 year ago 205
ASP.NET (C#) Question

ASP.Net Core Nested Area

I want to create area like the following structure


  • Areas


    • Admin


      • FrontEnd


        • Controllers


          • HomeController.cs


        • Views


      • API


        • Controllers


          • HomeController.cs







Startup class

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseMvc(routes =>
{
routes.MapRoute(name: "areaRoute",
template: "{area:exists}/{controller=Home}/{action=Index}");

routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}


I already marked [Area("Admin/FrontEnd")] to HomeController but it doesn't work. It return the following error

An unhandled exception occurred while processing the request.

InvalidOperationException: The view 'About' was not found. The following locations were searched:
/Areas/Admin/Views/Home/About.cshtml

How can I do?

Project

enter image description here

enter image description here

Answer Source

You can use the AreaViewLocationFormats on RazorViewEngineOptions to indicate what all paths you want MVC to look for views.

services.Configure<RazorViewEngineOptions>(o =>
{
    o.AreaViewLocationFormats.Insert(0, "/Areas/{2}/FrontEnd/Views/Shared/{0}.cshtml");
    o.AreaViewLocationFormats.Insert(0, "/Areas/{2}/FrontEnd/Views/{1}/{0}.cshtml");
});

You can read the detailed documentation on what AreaViewLocationFormats is over here: https://github.com/aspnet/Mvc/blob/1.0.0/src/Microsoft.AspNetCore.Mvc.Razor/RazorViewEngineOptions.cs#L92

Also you can just decorate your controllers to be just [Area("Admin")]