'Areas do not work in ASP.NET 6 with Angular project

I have created an dotnet angular project with the command:

dotnet new angular -o my-new-app

My app is working fine. But now I want to add areas in the controller. My sample code is given bellow:

Program.cs file:

app.MapControllerRoute("areas", "{areas:exist}/{controller}/{action=Index}/{id?}");

proxy.conf.js file

const PROXY_CONFIG = [
  {
    context: [
       "/Sys/airport",
   ],
    target: target,
    secure: false,
    headers: {
      Connection: 'Keep-Alive'
    }
  }
]

Controller file

[ApiController]
[Route("[area]/[controller]")]
[Area("Sys")]

Folder Structure

Areas\Sys\Controllers
AirportController.cs

Api URL

'/sys/airport/GetGridData'

Now data is coming without using area. But when I use area it shows 404 error.

Can any any one help me?



Solution 1:[1]

If GetGridData is a View, you should add below code in Program.cs file.

using Microsoft.AspNetCore.Mvc.Razor;

var builder = WebApplication.CreateBuilder(args);
// add below code
builder.Services.Configure<RazorViewEngineOptions>(options =>
{
    options.AreaViewLocationFormats.Clear();
    options.AreaViewLocationFormats.Add("/areas/{2}/Views/{1}/{0}.cshtml");
    options.AreaViewLocationFormats.Add("/areas/{2}/Views/Shared/{0}.cshtml");
    options.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
});

...

app.MapControllerRoute("areas", "{areas:exist}/{controller}/{action=Index}/{id?}");
app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");;

app.Run();

If your GetGridData is a api interface, it's ok, you don't need add code above. Whatever GetGridData is, we need to add [HttpGet("GetGridData")] to the method. This should fix the issue.

using Microsoft.AspNetCore.Mvc;

namespace my_new_app.Areas.Sys.Controllers
{
    [ApiController]
    [Route("[area]/[controller]")]
    [Area("Sys")]
    public class AirportController : Controller
    {
        // add this attribute
        [HttpGet("GetGridData")]
        public IActionResult GetGridData()
        {
            return View();
        }
        // add this attribute
        [HttpGet("GetGridData1")]
        public string GetGridData1()
        {
            return "111";
        }
    }
}

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 Jason