MVC 에서 Areas 사용하기

  • 4 minutes to read

이 문서는 .NET 8 이상 환경에서 Visual Studio 또는 CLI를 사용하여 MVC 프로젝트에서 Areas 기능을 적용하는 방법을 단계별로 안내합니다. 폴더 구조, 컨트롤러, 뷰, 라우팅까지 모두 포함하여 완성된 형태로 설명합니다.

목표

  • ASP.NET Core MVC 프로젝트를 생성합니다.
  • Areas 폴더를 활용하여 Security 영역을 구성합니다.
  • 관리자와 사용자 전용 컨트롤러 및 View 를 생성합니다.
  • 웹 브라우저에서 URL 접속 시 각 Area 별로 View 가 정상 출력되도록 설정합니다.

최종적으로 다음과 같은 URL로 접근할 수 있습니다.

  • /security/adminallowedipranges
  • /security/userallowedipranges

Step 1: 프로젝트 생성

Visual Studio 를 사용하는 경우 다음 순서를 따릅니다.

  1. Visual Studio 를 실행합니다.
  2. 새 프로젝트 만들기에서 ASP.NET Core 웹 앱 (모델-뷰-컨트롤러)을 선택합니다.
  3. 프로젝트 이름을 Azunt.Web 으로 설정합니다.
  4. .NET 8.0 또는 사용 가능한 버전을 선택합니다.
  5. 인증은 "없음"으로 설정하고, Docker 또는 HTTPS 옵션은 필요에 따라 선택합니다.
  6. 프로젝트를 생성합니다.

CLI 를 사용하는 경우 다음 명령어를 실행합니다.

dotnet new mvc -n Azunt.Web
cd Azunt.Web

Step 2: Areas 폴더 생성

프로젝트 루트에 Areas 폴더를 생성하고, 그 안에 Security 폴더를 추가합니다. Security 폴더 내에는 Controllers 폴더와 Views 폴더를 생성합니다.

폴더 구조는 다음과 같습니다.

/Areas
└── /Security
    ├── /Controllers
    └── /Views

Areas 폴더는 MVC 에서 기능별로 컨트롤러와 뷰를 분리하여 관리할 때 사용합니다.

Step 3: 컨트롤러 생성

Areas/Security/Controllers 폴더에 두 개의 컨트롤러 파일을 생성합니다.

먼저, AdminAllowedIpRangesController.cs 파일을 생성하고 다음과 같이 작성합니다.

using Microsoft.AspNetCore.Mvc;

namespace Azunt.Web.Areas.Security.Controllers
{
    [Area("Security")]
    public class AdminAllowedIpRangesController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

다음으로, UserAllowedIpRangesController.cs 파일을 생성하고 다음과 같이 작성합니다.

using Microsoft.AspNetCore.Mvc;

namespace Azunt.Web.Areas.Security.Controllers
{
    [Area("Security")]
    public class UserAllowedIpRangesController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Step 4: View 생성

Areas/Security/Views 폴더 안에 컨트롤러 이름에 맞는 폴더를 각각 생성합니다.

폴더 구조는 다음과 같습니다.

/Areas/Security/Views/AdminAllowedIpRanges/Index.cshtml
/Areas/Security/Views/UserAllowedIpRanges/Index.cshtml

AdminAllowedIpRanges 폴더 안에 Index.cshtml 파일을 생성하고 다음과 같이 작성합니다.

<h1>AdminAllowedIpRanges</h1>

UserAllowedIpRanges 폴더 안에 Index.cshtml 파일을 생성하고 다음과 같이 작성합니다.

<h1>UserAllowedIpRanges</h1>

Step 5: Program.cs 에 Areas 지원 추가

프로젝트의 Program.cs 파일을 열고 Areas 지원을 위한 라우팅 구성을 추가합니다.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

// Areas 라우팅을 먼저 등록합니다.
app.MapControllerRoute(
    name: "areas",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);

// 기본 라우팅을 추가합니다.
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}"
);

app.Run();

Areas 라우팅은 기본 라우팅보다 먼저 등록해야 Areas 에 정의된 컨트롤러가 우선적으로 인식됩니다.

Step 6: 실행 및 확인

Visual Studio 를 사용하는 경우 F5 또는 Ctrl + F5 키를 눌러 프로젝트를 실행합니다.

CLI 를 사용하는 경우 다음 명령어를 입력하여 실행합니다.

dotnet run

브라우저를 열고 다음 URL 에 접속하여 결과를 확인합니다.

  • /security/adminallowedipranges
  • /security/userallowedipranges

각 페이지에서 "AdminAllowedIpRanges" 와 "UserAllowedIpRanges" 라는 제목이 출력되면 정상적으로 구성된 것입니다.

완료

이제 Areas 구조를 활용하여 Security 영역 아래에 Admin 과 User 전용 컨트롤러와 View 를 분리하여 구성하는 작업을 마쳤습니다. Areas 를 사용하면 기능별로 코드를 효과적으로 분리할 수 있으며, 프로젝트 규모가 커지더라도 유지보수와 관리가 훨씬 수월해집니다.

VisualAcademy Docs의 모든 콘텐츠, 이미지, 동영상의 저작권은 박용준에게 있습니다. 저작권법에 의해 보호를 받는 저작물이므로 무단 전재와 복제를 금합니다. 사이트의 콘텐츠를 복제하여 블로그, 웹사이트 등에 게시할 수 없습니다. 단, 링크와 SNS 공유, Youtube 동영상 공유는 허용합니다. www.VisualAcademy.com
박용준 강사의 모든 동영상 강의는 데브렉에서 독점으로 제공됩니다. www.devlec.com