.net core 정적 미들웨어 사용

본문
정적 파일 호출 사용:

app.UseStaticFiles();
이 기본 값 은 루트 디 렉 터 리 의 wwwroot 를 정적 디 렉 터 리 로 합 니 다.
이것 은 비교적 주의해 야 할 것 입 니 다..........................................................................
그럼요.인 자 를 설정 할 수 있 습 니 다.UseStatic Files 에 인 자 를 전달 할 수 있 습 니 다.그러나 이것 은 묵인 적 인 약속 이기 때문에 이렇게 하지 말 것 을 건의 합 니 다.
ww wroot 아래 index.html 를 만 들 면 접근 합 니 다.http://localhost/index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
        
</body>
</html>
효과:

등록 해 야 할 다른 디 렉 터 리 가 있다 면 이렇게 할 수 있 습 니 다.

app.UseStaticFiles(new StaticFileOptions
{
	RequestPath="/files",
	FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"files"))
});
루트 디 렉 터 리 에 files 만 들 기:

그리고 방문 은http://localhost:5000/files/index.html
다음은 UseDefault Files 를 소개 합 니 다.이것 은 기본 파일 을 설정 하 는 것 입 니 다.
이 건 404 가 아니 라 이 파일 로 넘 어가 세 요.
중간 부품 사 이 를 직접 보 세 요.
DefaultFilesMiddleware:

public Task Invoke(HttpContext context)
{
	if (context.GetEndpoint() == null &&
		Helpers.IsGetOrHeadMethod(context.Request.Method)
		&& Helpers.TryMatchPath(context, _matchUrl, forDirectory: true, subpath: out var subpath))
	{
		var dirContents = _fileProvider.GetDirectoryContents(subpath.Value);
		if (dirContents.Exists)
		{
			// Check if any of our default files exist.
			for (int matchIndex = 0; matchIndex < _options.DefaultFileNames.Count; matchIndex++)
			{
				string defaultFile = _options.DefaultFileNames[matchIndex];
				var file = _fileProvider.GetFileInfo(subpath.Value + defaultFile);
				// TryMatchPath will make sure subpath always ends with a "/" by adding it if needed.
				if (file.Exists)
				{
					// If the path matches a directory but does not end in a slash, redirect to add the slash.
					// This prevents relative links from breaking.
					if (!Helpers.PathEndsInSlash(context.Request.Path))
					{
						context.Response.StatusCode = StatusCodes.Status301MovedPermanently;
						var request = context.Request;
						var redirect = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path + "/", request.QueryString);
						context.Response.Headers[HeaderNames.Location] = redirect;
						return Task.CompletedTask;
					}

					// Match found, re-write the url. A later middleware will actually serve the file.
					context.Request.Path = new PathString(context.Request.Path.Value + defaultFile);
					break;
				}
			}
		}
	}

	return _next(context);
}
안에서 하 는 일 은 간단 해서 요청 을 파일 경로 로 변환 합 니 다.끝에서부터
예 를 들 면http://localhost/a/,그럼 wwroot/a/경로 로 전환 합 니 다.그리고 context.Request.Path 의 끝 이/인지 판단 합 니 다.만약 그렇다면 파일 경로 에 index.html 또는 다른 기본 파일 을 추가 합 니 다.존재 한다 고 판단 되면 파일 을 되 돌려 줍 니 다.
예 를 들 면http://localhost/a,그럼 wwroot/a/경로 로 전환 합 니 다.그리고 context.Request.Path 의 끝 이/인지 판단 합 니 다.만약 그렇다면 파일 경로 에 index.html 또는 다른 기본 파일 을 추가 합 니 다.존재 한다 고 판단 되면 경로 에/를 추가 하고 301 로 돌아 가 다시 요청 합 니 다.
기본 값 은 Default Files Options:

/// <summary>
/// Options for selecting default file names.
/// </summary>
public class DefaultFilesOptions : SharedOptionsBase
{
	/// <summary>
	/// Configuration for the DefaultFilesMiddleware.
	/// </summary>
	public DefaultFilesOptions()
		: this(new SharedOptions())
	{
	}

	/// <summary>
	/// Configuration for the DefaultFilesMiddleware.
	/// </summary>
	/// <param name="sharedOptions"></param>
	public DefaultFilesOptions(SharedOptions sharedOptions)
		: base(sharedOptions)
	{
		// Prioritized list
		DefaultFileNames = new List<string>
		{
			"default.htm",
			"default.html",
			"index.htm",
			"index.html",
		};
	}

	/// <summary>
	/// An ordered list of file names to select by default. List length and ordering may affect performance.
	/// </summary>
	public IList<string> DefaultFileNames { get; set; }
}
위 에 있 는 이 몇 개의 기본 적 인 것 이 있 습 니 다.이것 은 순서에 따라 물론 당신 도 들 어가 서 수정 할 수 있 습 니 다.매개 변 수 를 보면 됩 니 다.

a 디 렉 터 리 에 index.html 을 만 들 었 습 니 다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
      a   index.html
</body>
</html>
그러면 방문http://localhost:5000/a 됐어.
효과:


301 번 지 났 는데.
그럼 디 렉 터 리 미리 보기 소개:
서비스 추가:
services.AddDirectoryBrowser();
미들웨어 증가:
app.UseDirectoryBrowser();

이렇게 하면 돼.
우리 앞 뒤 가 이렇게 불완전 하 게 분 리 된 상황 에 문제 가 있다 면.
예 를 들 어 지금 은 보통 3 대 프레임,vue 와 angular,react 라 는 말 이 있다.너 는 그들 이 자신의 길 을 가지 고 있다 는 문 제 를 발견 할 것 이다.
이 럴 때 우리 의 경로 와 충돌 할 수도 있다.
예 를 들 어http://localhost/pay방문 해 야 할 것 은 index.html 이다.index.html 는 자신의 경로 가 있 기 때문에 pay 페이지 를 표시 합 니 다.
그럼 길 을 설정 할 때 하 나 를 추가 해 야 합 니 다.

app.MapWhen(context =>
{
	return !context.Request.Path.Value.StartsWith("/api");
}, builder =>
{
	var option = new RewriteOptions();
	option.AddRewrite(".*","/index.html",true);
	app.UseRewriter(option);
	app.UseStaticFiles();
});
즉,/api 가 시작 하지 않 으 면 index.html 로 통일 적 으로 위치 한 다음 에 UseStaticFiles 처 리 를 통 해 index.html 로 바로 갑 니 다.
RewriteOptions 이 변환 들 은 세부 편 에서 소개 합 니 다.물론 HttpContext body 에 index.html 흐름 을 직접 주입 하고 돌아 갈 수도 있 지만 다른 특성 이 없 으 면 소개 하지 않 습 니 다.
맺다.
이상 은.net core 정적 미들웨어 의 사용 에 대한 상세 한 내용 입 니 다.더 많은.net core 정적 미들웨어 에 관 한 자 료 는 우리 의 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기