ASP.NET Core 애플리케이션에서 HTML, CSS, JavaScript, 이미지와 같은 리소스는 정적 파일로 분류되며, 서버가 이를 클라이언트에 직접 제공합니다. 이러한 정적 파일 관리를 위해 ASP.NET Core는 미들웨어 기반의 유연한 구성 방식을 제공합니다.
1. 기본 경로 및 설정
기본적으로 정적 파일은 프로젝트의 웹 루트(Web Root) 디렉터리인 wwwroot 폴더 내에 위치합니다. 개발 환경에서 웹 루트가 정확히 인식되도록 하기 위해 다음과 같이 콘텐츠 루트를 설정할 수 있습니다.
var builder = WebApplication.CreateBuilder(args);
// 현재 디렉터리를 콘텐츠 루트로 명시적 설정
builder.Host.UseContentRoot(Directory.GetCurrentDirectory());
var app = builder.Build();
웹 루트 내의 파일은 상대 경로를 통해 접근 가능합니다. 예를 들어 wwwroot/images/logo.png 파일은 https://<server>/images/logo.png 주소로 호출됩니다. 이를 활성화하려면 미들웨어 파이프라인에 app.UseStaticFiles()를 추가해야 합니다.
2. 외부 디렉터리 파일 제공
보안이나 관리 목적으로 wwwroot 외부의 폴더에 있는 파일을 서비스해야 할 경우가 있습니다. 이때는 StaticFileOptions를 사용하여 물리적 경로와 요청 경로를 매핑합니다.
var sharedPath = Path.Combine(builder.Environment.ContentRootPath, "ExternalAssets");
// 외부 디렉터리용 정적 파일 미들웨어 추가
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(sharedPath),
RequestPath = "/cdn"
});
위 설정에 따라 ExternalAssets/sample.jpg 파일은 /cdn/sample.jpg 경로로 접근할 수 있게 됩니다.
3. 정적 파일 보안 및 권한 제어
정적 파일 미들웨어는 기본적으로 별도의 권한 검사를 수행하지 않습니다. 즉, 파일 경로를 아는 모든 사용자에게 파일이 공개됩니다. 특정 권한이 있는 사용자에게만 파일을 제공하려면 다음 전략을 권장합니다.
- 파일을
wwwroot외부에 저장하여 직접적인 HTTP 접근을 차단합니다. - Controller의 Action 내에서 권한을 검증한 뒤
FileResult를 반환하여 파일을 제공합니다.
4. 디렉터리 브라우징 활성화
보안상 디렉터리 브라우징은 기본적으로 비활성화되어 있습니다. 하지만 내부 네트워크나 관리 페이지 등에서 파일 목록을 보여줘야 한다면 UseDirectoryBrowser를 활용할 수 있습니다.
// 서비스 등록
builder.Services.AddDirectoryBrowser();
// 미들웨어 설정
var folderPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "docs");
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(folderPath),
RequestPath = "/SharedDocs"
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new PhysicalFileProvider(folderPath),
RequestPath = "/SharedDocs"
});
5. 기본 페이지(Default Files) 설정
사용자가 특정 파일명을 입력하지 않고 디렉터리 경로만 입력했을 때(예: /) 자동으로 제공할 기본 페이지를 설정할 수 있습니다. UseDefaultFiles는 반드시 UseStaticFiles보다 먼저 호출되어야 합니다.
DefaultFilesOptions defaultOptions = new DefaultFilesOptions();
defaultOptions.DefaultFileNames.Clear();
defaultOptions.DefaultFileNames.Add("main.html");
app.UseDefaultFiles(defaultOptions);
app.UseStaticFiles();
6. UseFileServer 통합 미들웨어
UseStaticFiles, UseDefaultFiles, UseDirectoryBrowser 기능을 하나로 묶어 제공하는 것이 UseFileServer입니다. 간단한 설정만으로 복합적인 파일 서비스를 구축할 수 있습니다.
app.UseFileServer(new FileServerOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "PrivateFiles")),
RequestPath = "/files",
EnableDirectoryBrowsing = true
});
7. MIME 유형 구성
ASP.NET Core가 인식하지 못하는 확장자의 경우 보안을 위해 404 에러를 반환합니다. 이를 해결하려면 FileExtensionContentTypeProvider를 통해 새로운 매핑을 정의해야 합니다.
var typeProvider = new FileExtensionContentTypeProvider();
// 특정 확장자 추가
typeProvider.Mappings[".data"] = "application/octet-stream";
// 기존 확장자 삭제
typeProvider.Mappings.Remove(".mp4");
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = typeProvider
});
알 수 없는 모든 파일 형식을 처리하려면 ServeUnknownFileTypes 속성을 사용할 수 있으나, 이는 보안 취약점을 야기할 수 있으므로 주의해서 사용해야 합니다.