본문 바로가기
IT/C#

C#으로 Web 개발 방법

by eplus 2024. 12. 1.

C#으로 Web App을 개발하는 과정을 단계별로 더 자세히 설명드리겠습니다. 여기서는 ASP.NET Core를 사용한 개발을 기준으로 설명합니다.


1. 개발 환경 설정

  1. Visual Studio 설치
    • Visual Studio Community 버전은 무료로 사용할 수 있습니다.
    • 설치할 때 ASP.NET 및 웹 개발 워크로드를 선택합니다.
  2. .NET SDK 설치
    • .NET SDK 다운로드 페이지에서 최신 SDK를 설치합니다.
    • 설치 후 명령어 확인:
      dotnet --version
      
  3. SQL Server 설치 (선택 사항)
    • 데이터베이스가 필요하면 SQL ServerSQLite, MySQL 등을 설치합니다.

2. 프로젝트 생성

  1. Visual Studio에서 새 프로젝트 생성
    • "파일 > 새로 만들기 > 프로젝트"를 선택.
    • "ASP.NET Core Web App (Model-View-Controller)" 또는 "ASP.NET Core Web API" 템플릿 선택.
    • 프로젝트 이름 및 저장 경로 설정.
  2. 템플릿 구성
    • .NET 6 이상을 사용하는 경우, Program.cs와 Startup.cs 파일이 통합되어 있습니다.
    • 추가 구성 없이 기본 템플릿으로 실행 가능.

3. 프로젝트 구조 이해

  1. Program.cs
    • ASP.NET Core 앱의 진입점.
    • 서비스 등록 및 미들웨어 구성을 설정.
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    
  2. Controllers
    • 비즈니스 로직을 처리하고 데이터를 View에 전달.
    • 예제: HomeController.cs
      public class HomeController : Controller
      {
          public IActionResult Index()
          {
              return View();
          }
      }
      
  3. Views
    • 사용자 인터페이스를 구성하는 파일.
    • Razor 문법을 사용해 C# 코드를 HTML에 삽입.
    • 예제: Views/Home/Index.cshtml
      <h1>Welcome to ASP.NET Core!</h1>
      
  4. Models
    • 데이터 구조 및 비즈니스 로직을 정의.
    • 예제:
      public class Product
      {
          public int Id { get; set; }
          public string Name { get; set; }
          public decimal Price { get; set; }
      }
      

4. 데이터베이스 연동

  1. Entity Framework Core 설치
    • NuGet Package Manager를 사용해 EF Core 패키지 설치:
      Install-Package Microsoft.EntityFrameworkCore.SqlServer
      Install-Package Microsoft.EntityFrameworkCore.Tools
      
  2. DbContext 생성
  3. public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } }
  4. 서비스에 DbContext 등록
  5. builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
  6. 마이그레이션 및 데이터베이스 생성
  7. dotnet ef migrations add InitialCreate dotnet ef database update

5. 미들웨어 구성

  1. 미들웨어 파이프라인 설정
    • 요청/응답 파이프라인에 미들웨어 추가.
    • 예: UseAuthentication(), UseAuthorization().
  2. Static Files
    • wwwroot 폴더에 정적 파일 추가 (CSS, JS, 이미지 등).

6. 기능 개발

  1. 라우팅 설정
    • MapControllerRoute 또는 MapGet으로 라우팅 설정.
    • 예제:
      app.MapControllerRoute(
          name: "default",
          pattern: "{controller=Home}/{action=Index}/{id?}");
      
  2. CRUD API 개발
    • Web API 템플릿을 사용해 RESTful API를 개발.
    • 예제:
      [ApiController]
      [Route("api/[controller]")]
      public class ProductsController : ControllerBase
      {
          private readonly AppDbContext _context;
      
          public ProductsController(AppDbContext context)
          {
              _context = context;
          }
      
          [HttpGet]
          public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
          {
              return await _context.Products.ToListAsync();
          }
      
          [HttpPost]
          public async Task<ActionResult<Product>> PostProduct(Product product)
          {
              _context.Products.Add(product);
              await _context.SaveChangesAsync();
              return CreatedAtAction(nameof(GetProducts), new { id = product.Id }, product);
          }
      }
      

7. 테스트 및 디버깅

  • Visual Studio의 디버깅 도구를 활용해 로컬에서 테스트 (F5).
  • 브라우저로 URL 접속해 결과 확인.

8. 배포

  1. 로컬 서버 배포
    • Windows: IIS 사용.
    • Linux: Nginx 또는 Apache 사용.
  2. 클라우드 배포
    • Azure App Service:
      • Visual Studio에서 "게시"를 클릭하고 Azure에 바로 배포 가능.
    • AWS Elastic Beanstalk, Google App Engine도 지원.

추가 학습 자료

더 구체적인 내용이나 코드 예제가 필요하면 말씀해주세요!

728x90
반응형