asp.net core 정적 파일 자원 에 대한 심도 있 는 설명

머리말
정적 자원 에 대한 간단 한 개황 은 시리즈 뒤에 깊이 들 어 갈 것 이다.
본문
우리 가 중간 부품 에 가입 하 는 것 은 이렇게 쓴 것 이다.

app.UseStaticFiles();
기본적으로 wwroot 에 자원 을 제공 합 니 다.
그럼 방문 하 겠 습 니 다.https://localhost:44330/js/site.js 자원

// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

// Write your JavaScript code.
마찬가지 로 우 리 는 경 로 를 사용자 정의 할 수 있다.

app.UseStaticFiles(new StaticFileOptions {
	FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Static")),
	RequestPath="/static"
});
위 에 있 는 루트 디 렉 터 리 아래 의 static 는 루트 를 만 들 고 루트 는 static 로 표 시 됩 니 다.
접근:
https://localhost:44330/static/images/index.jpg
그림 한 장 이 보 입 니 다.
같은 재 방문,https://localhost:44330/js/site.js 여전히 방문 할 수 있 습 니 다.이 wwroot 는 못 을 박 은 사람 입 니 다.어쨌든 추가 하 더 라 도 존재 합 니 다.

const string cacheMaxAge = "60480";
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions {
	FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Static")),
	RequestPath="/static",
	OnPrepareResponse = ctx => {
		ctx.Context.Response.Headers.Append("cache-control", $"public,max-age={cacheMaxAge}");
	}
}
);
캐 시 를 설정 할 수 있 습 니 다.

정적 파일 권한 부여
정 부 는 두 가지 방법 을 제공 했다.
하 나 는 정적 파일 루트 를 권한 뒤에 두 는 것 이다.

app.UseAuthentication();
app.UseAuthorization();

app.UseStaticFiles(new StaticFileOptions
{
	FileProvider = new PhysicalFileProvider(
				 Path.Combine(env.ContentRootPath, "Static")),
	RequestPath = "/static"
});
다른 사용자 정의 높이:

[Authorize]
public IActionResult BannerImage()
{
 var filePath = Path.Combine(
  _env.ContentRootPath, "MyStaticFiles", "images", "red-rose.jpg");

 return PhysicalFile(filePath, "image/jpeg");
}
매개 변수 에 따라 논리 적 변 화 를 할 수 있다.
그러나 이런 방식 은 성능 에 영향 을 미친다.일반적으로 정적 파일 은 개방 적 이 고 사용자 가 업로드 한 파일 은 암호 화 를 통 해 저장 서버 에 놓는다.
물론 소형 프로젝트 로 사용 할 수 있 습 니 다.
정적 파일 디 렉 터 리
Configure 에 추가:

app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
	FileProvider=new PhysicalFileProvider(Path.Combine(env.ContentRootPath,"Static")),
	RequestPath="/static"
});
이 미들웨어 가 주입 하 는 위 치 는 UseRouting 이전에 있어 야 하 며,마찬가지 로 성능 문제 이다.
그리고 Configure Services 에 추가:

services.AddDirectoryBrowser();
효과:

이런 방식 은 보통 dev 환경 에서 만 열 리 고 진정한 생산 환경 은 안전 문제 로 인해 열 리 지 않 습 니 다.
기본 문서

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseStaticFiles(); 진정한 길이 다.
app.UseDefaultFiles(); 기본 항목 으로 설정 하 는 등 파 라 메 터 를 제공 합 니 다.

default.htm
default.html
index.htm
index.html
사실은 이러한 과정 입 니 다.app.UseStaticFiles()가 해당 하 는 길 을 찾 지 못 하면 다음 미들웨어 를 주어 야 합 니 다.
app.UseDefault Files()를 호출 하면 기본 항목 이 있 는 지 찾 습 니 다.기본 값 은 wwroot 에서 위 와 같은 기본 항목 을 찾 습 니 다.
기본 문 서 를 수정 할 수 있 습 니 다:

var options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mydefault.html");
app.UseDefaultFiles(options);
app.UseStaticFiles();
UseFileServer 는 UseStaticFiles,UseDefaultFiles,UseDirectory Browser(선택 가능)기능 을 결합 했다.
app.UseFileServer(enableDirectoryBrowsing: true);
enableDirectoryBrowsing 은 UseDirectoryBrowser 를 사용 할 지 여 부 를 표시 합 니 다.
FileExtensionContentTypeProvider
FileExtension ContentTypeProvider 클래스 는 Mappings 속성 을 포함 하여 파일 확장자 가 MIME 콘 텐 츠 형식 에 대한 맵 으로 사 용 됩 니 다.
예 를 들 어 내 가 방문 하 러 간다.https://localhost:44330/static/test.myapp
static 에 test.map 파일 이 있 지만 정적 파일 처 리 는 처리 되 지 않 았 습 니 다.
원인:

고객 센터 에서 이러한 요청 을 보 냈 습 니 다.사람들 은 이러한 흐름 을 받 아들 이지 만 서버 에서 my app 에 대응 하 는 미디어 유형 을 찾 았 습 니 다.그러면 이 럴 때 클 라 이언 트 가 받 아들 이지 않 고 서버 에서 도 찾 지 못 했다 고 생각 합 니 다.
공식 적 으로 예 를 들 었 다.

var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4");

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
	FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Static")),
	RequestPath = "/static",
	OnPrepareResponse = ctx => {
		ctx.Context.Response.Headers.Append("cache-control", $"public,max-age={cacheMaxAge}");
	},
	ContentTypeProvider= provider
}
그 에 게 미디어 형식 을 추가 하여 my app 은 파일 을 다운로드 해 야 한다 고 생각 합 니 다.
그리고 실행 하면 다운로드 가 나 옵 니 다.
마찬가지 로,우리 가 쓴 것 은.html 입 니 다.만약 우리 가 좋아 하지 않 는 다 면.htm 3 를 써 도 됩 니 다.
https://localhost:44330/static/index.htm3
결과:
provider.Mappings[".htm3"] = "text/html"; htm 3 이 text/html 로 매 핑 되 었 기 때문에 클 라 이언 트 는 이러한 형식 으로 처리 합 니 다.그래서 템 플 릿 엔진 은 다양성 을 가 질 수 있 고 관심 이 있 으 면 자신 도 디자인 할 수 있다.
이것 이 바로 미디어 형식 맵 입 니 다.
미디어 형식 이 알 수 없 는 상황 이 라면 이렇게 할 수 있 습 니 다.

app.UseStaticFiles(new StaticFileOptions
{
	FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Static")),
	RequestPath = "/static",
	OnPrepareResponse = ctx => {
		ctx.Context.Response.Headers.Append("cache-control", $"public,max-age={cacheMaxAge}");
	},
	ServeUnknownFileTypes = true,
	DefaultContentType = "image/png"
}
);
ServeUnknownFileTypes true
Default ContentType"image/png"는 클 라 이언 트 가 그림 에 따라 처리 하도록 합 니 다.

하지만 공식 적 으로 조언 을 해 줬 다.
ServeUnknown FileTypes 를 사용 하면 안전 위험 이 발생 합 니 다.기본적으로 사용 하지 않 는 상태 입 니 다.사용 을 권장 하지 않 습 니 다.
FileExtension ContentTypeProvider 는 표준 확장자 가 아 닌 파일 을 제공 하 는 보다 안전 한 대체 방법 을 제공 합 니 다.
총결산
asp.net core 정적 파일 자원 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 asp.net core 정적 파일 자원 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 바 랍 니 다!

좋은 웹페이지 즐겨찾기