본문 바로가기

카테고리 없음

Azure Storage + ASP.NET Core 8 파일 관리 API 구축하기 (로컬 + Emulator 환경)


Azure Storage + ASP.NET Core 8 파일 관리 API 구축하기 (로컬 + Emulator 환경)

최근 진행한 실습 기록을 정리한다. 목표는 다음과 같다.
• Azure Storage Emulator(Azurite) 기반 로컬 개발
• Azure Blob, Fileshare 업로드/다운로드 API
• MSSQL DB에 메타데이터 저장
• 배포 모드에서는 DB 저장만 수행
• .NET 8 Web API + 콘솔 클라이언트 개발

아래는 단계별로 진행한 내용과, 검색 키워드 예시와 구현 힌트를 정리한 글이다.



1. Azure Storage 개발 환경 준비

Azurite 설치

로컬에서 Azure Blob/Fileshare를 테스트하기 위해 Azurite를 설치했다. Node.js가 있다면 아래 명령어로 간단히 설치 가능하다.

 

npm install -g azurite

azurite

또는 Docker로도 쉽게 띄울 수 있다.

docker run -p 10000:10000 -p 10001:10001 -p 10002:10002 mcr.microsoft.com/azure-storage/azurite


설치 후에는 포트 10000(Blob), 10001(Queue), 10002(Table)이 열려 있는지 확인한다.

참고 

Azurite Azure Storage Emulator install
Azurite quickstart guide




2. Azure Storage Explorer 설치

Azure Storage Explorer는 Storage 계정 및 Emulator 관리용 GUI 도구이다. 아래 검색어로 다운로드 페이지를 찾았다.

Azure Storage Explorer download

설치 후에는 Emulator와 연결해 컨테이너를 생성하고 목록을 조회해 보았다. Emulator 연결은 “Local & Attached” 섹션에서 Development Storage 문자열을 사용하면 된다.

UseDevelopmentStorage=true



추가 

Azure Storage Explorer connect to emulator




2. MSSQL 설치 및 DB 준비

SQL Server 설치

프로젝트에서는 메타데이터를 저장할 DB가 필요했다. 무료 Developer 버전을 선택했다.



SQL Server Developer Edition download

설치 후에는 SQL Server Management Studio(SSMS)도 함께 설치해 쿼리를 쉽게 관리했다.



DB/테이블 생성

파일 메타데이터를 관리할 테이블을 만들었다. 아래 예제는 SSMS에서 사용한 스크립트이다.

CREATE TABLE FileMetadata (
    Id INT PRIMARY KEY IDENTITY,
    FileName NVARCHAR(255),
    StorageType NVARCHAR(50),
    PathOrUrl NVARCHAR(500),
    ExpireAt DATETIME NULL,
    Encrypted BIT,
    CreatedAt DATETIME DEFAULT GETDATE()
);




SQL Server create database and table script
SSMS create table GUI




3. ASP.NET Core 8 Web API 생성

새 프로젝트 만들기

터미널에서 .NET CLI를 사용해 Web API 템플릿을 생성했다.

dotnet new webapi -n FileStorageApi
cd FileStorageApi
dotnet run



실행 후 Swagger UI가 뜨는 것을 확인했다.


추가참고
dotnet new webapi
ASP.NET Core 8 Web API tutorial




4. DTO와 모델 설계

API 요청/응답 구조를 정의했다. 업로드 옵션을 담는 DTO 클래스를 아래처럼 작성했다.

public enum StorageType
{
    FileShare,
    Blob,
    OnPremise
}

public class UploadOption
{
    public DateTime? Expire { get; set; }
    public bool Encrypt { get; set; }
    public StorageType Type { get; set; }
}

 

 

 

추가 참고
ASP.NET Core create DTO class




5. DB 연동 (Entity Framework Core)

프로젝트에서 SQL Server와 연결하려고 Entity Framework Core를 사용했다.

NuGet 패키지 설치

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools



DbContext 생성 예제

public class AppDbContext : DbContext
{
    public DbSet<FileMetadata> FileMetadata { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options) { }
}



appsettings.json

"ConnectionStrings": {
  "DefaultConnection": "Server=localhost;Database=YourDb;Trusted_Connection=True;"
}


Program.cs

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));


Migration

dotnet ef migrations add InitialCreate
dotnet ef database update



추가 참고

ASP.NET Core Entity Framework Core SQL Server
ASP.NET Core Repository pattern example
EF Core migration tutorial




6. Storage Service 설계 및 구현

Azure Blob, Fileshare 업로드/다운로드 기능을 담당하는 인터페이스를 정의했다.

public interface IStorageService
{
    Task UploadAsync(IFormFile file, UploadOption option);
    Task<Stream> DownloadAsync(string id);
    Task RemoveAsync(string id);
    Task CopyAsync(string sourceId, string targetPath);
    Task MoveAsync(string id, string newPath);
    Task<IEnumerable<string>> GetDirectories();
    Task<IEnumerable<string>> GetFiles(string directory);
    Task<FileDetail> GetFile(string id);
    Task<DirectoryDetail> GetDirectory(string id);
}



Azure Storage SDK 예제 코드 참조

추가 참고

C# Azure Blob Storage SDK example
C# Azure File Share SDK example
Azurite connection string C#

Azurite Emulator 접속 문자열 예제

UseDevelopmentStorage=true






7. 환경 분기 처리

배포 시에는 실제 Storage 업로드를 하지 않고 DB에만 저장하도록 분기처리를 구현했다.

IHostEnvironment 사용 예제

if (_env.IsDevelopment())
{
    // Emulator에 업로드
}
else
{
    // DB 기록만
}

appsettings.Development.json

"StorageSettings": {
  "Environment": "Local",
  "ConnectionString": "UseDevelopmentStorage=true"
}

appsettings.Production.json

"StorageSettings": {
  "Environment": "Production",
  "ConnectionString": ""
}



검색어

ASP.NET Core IHostEnvironment example
ASP.NET Core appsettings environment specific




8. Web API 컨트롤러 작성

파일 업로드/다운로드/삭제/조회 엔드포인트를 구현했다. 아래는 간단한 업로드 예제이다.

[HttpPost("upload")]
public async Task<IActionResult> Upload(List<IFormFile> files, [FromQuery] UploadOption options)
{
    foreach (var file in files)
    {
        await _storageService.UploadAsync(file, options);
    }
    return Ok();
}



추가 참고

ASP.NET Core upload download file Web API
ASP.NET Core multiple file upload example




9. 클라이언트 콘솔 앱 작성

API를 호출하는 콘솔 클라이언트를 별도로 작성했다. HttpClient를 사용해 파일 업로드를 구현했다.

var client = new HttpClient();
var content = new MultipartFormDataContent();
// 파일 스트림 추가 코드 생략
await client.PostAsync("https://localhost:5001/api/upload", content);


추가 참고
C# HttpClient call Web API example
C# console app user input




10. 테스트

마지막으로 로컬 개발환경(Development)에서는 Azurite를 통해 실제 업로드/다운로드가 동작하는지 확인했다.
프로덕션 모드에서는 업로드 없이 DB에 메타데이터만 저장되는지 점검했다.

dotnet run --environment "Development"
dotnet run --environment "Production"

 



추가 참고
ASP.NET Core environment variables deployment




참고 키워드 모음

마지막으로 단계별 구글링 키워드를 한눈에 보기 좋게 정리해 두었다.
• Azurite Azure Storage Emulator install
• Azure Storage Explorer download
• Azure Storage Explorer connect to emulator
• SQL Server create database and table script
• dotnet new webapi
• ASP.NET Core 8 Web API tutorial
• ASP.NET Core create DTO class
• ASP.NET Core Entity Framework Core SQL Server
• ASP.NET Core Repository pattern example
• C# Azure Blob Storage SDK example
• C# Azure File Share SDK example
• Azurite connection string C#
• ASP.NET Core IHostEnvironment example
• ASP.NET Core appsettings environment specific
• ASP.NET Core upload download file Web API
• C# HttpClient call Web API example
• C# console app user input