basic06
์ฌ์ฉ์ ์ง์ ๋ฏธ๋ค์จ์ด์ ์ฌ์ฉ ๋ฐฉ๋ฒ์ ๋ํ ์์ ์ฝ๋์ ๋๋ค. ๋ฏธ๋ค์จ์ด๋ ๋ฑ๋กํ ์์๋๋ก ์คํ๋๊ธฐ์, program.cs์์ ์์๋ฅผ ์ ์ง์ ํด์ผ ํฉ๋๋ค.
program.cs
Routing๊ณผ Endpoint(Controller) ์ฌ์ด์ ๋ ๊ฐ์ง ๋ฏธ๋ค์จ์ด๊ฐ ์ฝ์ ๋์ด, ์ฝ์ ๋ ์์๋๋ก ์คํ๋จ
์ฌ์ฉ์ ์ง์ ๋ฏธ๋ค์จ์ด๋ [MiddlerWare] ๋๋ ํ ๋ฆฌ ์์ ์ ์๋์ด์์
// program.cs app.UseRouting(); app.UseLoadRequestDataMiddlerWare(); app.UseCheckUserSessionMiddleWare(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
LoadRequestDataMiddlerWare.cs
๋ฏธ๋ค์จ์ด๋ ํด๋์ค๋ก ์ ์๋์ด์ผ ํ๊ณ ๋ค์๊ณผ ๊ฐ์ ์์๋ฅผ ๊ฐ์ง๊ณ ์์ด์ผ ํจ
ํ๋ ์์ํฌ์์ ํด๋น ๋ฏธ๋ค์จ์ด ์คํ ํ ๋ค์ ๋ฏธ๋ค์จ์ด๊ฐ ๋์ํ ์ ์๊ฒ ํ๊ธฐ ์ํด์ ๋๋ฆฌ์(delegate)๋ฅผ ์ค์ ํด์ค์ผ ํจ
private readonly RequestDelegate _next; public LoadRequestDataMiddlerWare(RequestDelegate next) { _next = next; }๋ฏธ๋ค์จ์ด๊ฐ ์คํ๋๋ ์ฝ๋๋ Invoke ๋๋ InvokeAsync๋ผ๋ ๊ณต์ฉ ๋ฉ์๋์ ์ ์ ๋์ด์ผ ํจ
basic06์ ๊ฒฝ์ฐ
public async Task InvokeAsync(HttpContext context)๋ก ์ ์ ๋ฐ ๊ตฌํ ๋์ด ์์๋น๋๊ธฐ์์ผ๋ก ๊ตฌํํ๊ธฐ ์ํด์๋ InvokeAsync๋ฅผ ๊ตฌํํด์ผ ํจ
์ด ๋ฉ์๋๋ Task๋ฅผ ๋ฐํํด์ผ ํจ
์ ์ ํ ์์ ์ awit๋ก
_next(context)๋ฅผ ํธ์ถํ์ฌ ๋ค์ ๋ฏธ๋ค์จ์ ์คํ
CheckUserSessionMiddleWare.cs, LoggingMiddleware.cs๋ ์ด์ ๊ฐ์ ๊ตฌ์กฐ
_next(context)๋ฅผ ํธ์ถ๋ฏธ๋ค์จ์ด ๋ฉ์๋ ๋ด๋ถ์์ _next ๋ฏธ๋ค์จ์ด ๋ฉ์๋๋ฅผ ํธ์ถํ๊ธฐ ๋๋ฌธ์ ์๋ ๊ทธ๋ฆผ๊ณผ ๊ฐ์ ๊ตฌ์กฐ๋ก ์คํ๋๋ค๊ณ ๋ณผ ์ ์์
1. Middleware1 ๋ฉ์๋ ์์์ `await _next(context)`์ผ๋ก Middleware2 ๋ฉ์๋ ํธ์ถ. 2. Middleware2 ๋ฉ์๋ ์์์ ๋ `await _next(context)` Middleware3 ๋ฉ์๋ ํธ์ถ. 3. Middleware ๋ฉ์๋์์ ๊ณ์ํด์ next Middleware ๋ฉ์๋๋ฅผ ํธ์ถํจ 4. EndPoint Middleware(next๊ฐ ์๋ ๋ง์ง๋ง ๋ฏธ๋ค์จ์ด)์์๋ void ๋๋ ์ด๋ค ๊ฐ์ ๋ฆฌํดํ๋ฉด์ ์ข ๋ฃ. 5. ์ด์ ๋ฉ์๋์์ `await _next(context)`์ ๋ค์ ์ค ์ฝ๋๋ถํฐ ์ด์ด์ ๊ณ์ ์งํํ๋ค๊ฐ void ๋๋ ์ด๋ค ๊ฐ์ ๋ฆฌํดํ๋ฉด์ ์ข ๋ฃ. 6. ๋๊น์ง ๋์์์ ํ๋ ์์ํฌ ๋ด๋ถ์์ ๋์ํ๋ ๊ฐ์ฒด๊ฐ Response๋ฅผ ๋ณด๋
MiddlewareExtentions.cs
ํ์ฅ ๋ฉ์๋ ์ถ๊ฐํ๊ธฐ
์๋ ์ฝ๋๋ฅผ ์ถ๊ฐํ๊ธฐ ๋๋ฌธ์, program.cs์์ app.UseLoadRequestData(), app.UseCheckUserSessionMiddleWare()๋ฅผ ์ฌ์ฉํ ์ ์์;
public static class MiddlewareExtentions { public static IApplicationBuilder UseLoadRequestDataMiddlerWare(this IApplicationBuilder builder) { return builder.UseMiddleware<LoadRequestDataMiddlerWare>(); } public static IApplicationBuilder UseCheckUserSessionMiddleWare(this IApplicationBuilder builder) { return builder.UseMiddleware<CheckUserSessionMiddleWare>(); } }LoggingMiddlewareExtensions.cs๋ ์ด์ ๊ฐ์ ๊ตฌ์กฐ
Last updated