├── README.md
├── SUMMARY.md
├── components.md
├── debugging.md
├── dependency-injection.md
├── faq.md
├── get-started.md
├── host-and-deploy
├── README.md
├── configure-linker.md
└── hosting-models.md
├── introduction.md
├── javascript-interop.md
├── layouts.md
├── routing.md
└── tutorials
├── README.md
└── build-your-first-blazor-app.md
/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | description: >-
3 | 이 문서는 ASP.NET Blazor Preview Guide 문서를 한국어로 번역한 것으로, Experimental Release에 대한
4 | 문서를 커뮤니티를 위하여 정보 공유를 목적으로 미리 번역한 것입니다. 최신 버전의 내용을 반영하지 못할 수 있으나, 독자 여러분의 기여를
5 | 환영합니다.
6 | ---
7 |
8 | # ASP.NET Blazor 한국어 가이드
9 |
10 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
11 |
12 | 이 문서는 ASP.NET Blazor Preview Guide 문서 \([https://blazor.net/docs/index.html](https://blazor.net/docs/index.html)\) 를 한국어로 번역한 것으로, Experimental Release에 대한 문서를 커뮤니티를 위하여 정보 공유를 목적으로 미리 번역한 것입니다. 최신 버전의 내용을 반영하지 못할 수 있으나, 독자 여러분의 기여를 환영합니다.
13 |
14 | 이 문서에 대한 참여를 원하시면 [https://github.com/rkttu/asp-net-blazor-krguide](https://github.com/rkttu/asp-net-blazor-krguide) GitHub 리포지터리를 이용해주세요.
15 |
16 | ## 목차
17 |
18 | * [Blazor 시작하기](get-started.md)
19 | * [첫 Blazor 앱 만들기](tutorials/build-your-first-blazor-app.md)
20 | * [자주 묻는 질문들](faq.md)
21 | * [Blazor 소개](introduction.md)
22 | * [컴포넌트](components.md)
23 | * [레이아웃](layouts.md)
24 | * [의존성 주입](dependency-injection.md)
25 | * [라우팅](routing.md)
26 | * [자바스크립트 연동](javascript-interop.md)
27 | * [호스팅 및 배포](host-and-deploy/)
28 |
29 |
--------------------------------------------------------------------------------
/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # Table of contents
2 |
3 | * [ASP.NET Blazor 한국어 가이드](README.md)
4 | * [Blazor 시작하기](get-started.md)
5 | * [튜토리얼](tutorials/README.md)
6 | * [첫 Blazor 앱 만들기](tutorials/build-your-first-blazor-app.md)
7 | * [Blazor 소개](introduction.md)
8 | * [컴포넌트](components.md)
9 | * [레이아웃](layouts.md)
10 | * [의존성 주입](dependency-injection.md)
11 | * [라우팅](routing.md)
12 | * [자바스크립트 연동](javascript-interop.md)
13 | * [디버깅](debugging.md)
14 | * [호스팅 및 배포](host-and-deploy/README.md)
15 | * [호스팅 모델](host-and-deploy/hosting-models.md)
16 | * [링커 설정하기](host-and-deploy/configure-linker.md)
17 | * [자주 묻는 질문들](faq.md)
18 |
19 |
--------------------------------------------------------------------------------
/components.md:
--------------------------------------------------------------------------------
1 | # 컴포넌트
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | [샘플 코드를 보거나 다운로드하려면 여기를 클릭하세요.](https://github.com/aspnet/Blazor.Docs/tree/master/docs/common/samples/) \([다운로드하는 방법](https://blazor.net/docs/index.html#view-and-download-samples)\) [Blazor 시작하기](../get-started.md) 문서를 참고하여 미리 준비해야 할 내용을 확인하세요.
6 |
7 | Blazor 앱은 _컴포넌트_ 를 사용하여 만들어집니다. 컴포넌트는 페이지, 대화 상자 또는 양식과 같이 그 자체로 하나의 사용자 인터페이스 \(UI\) 조각입니다. 컴포넌트에는 화면에 그릴 HTML 마크업과, 데이터를 주입하거나 UI 이벤트에 응답하기 위한 처리 로직을 모두 포함하고 있습니다. 컴포넌트는 유연하며 매우 가볍고, 중첩되거나, 재사용되거나, 여러 프로젝트에 걸쳐 공유할 수 있습니다.
8 |
9 | ### 컴포넌트 클래스
10 |
11 | Blazor 컴포넌트는 보통 _|*.cshtml_ 파일 안에 C\#과 HTML 마크업을 조합하여 구현합니다. 컴포넌트의 UI는 HTML을 사용하여 정의됩니다. 동적 렌더링 로직 \(예를 들어, 반복문, 조건문, 표현식\)은 [Razor](https://docs.microsoft.com/aspnet/core/mvc/views/razor) 라는 내장된 C\# 문법을 사용하여 추가합니다. Blazor 앱이 컴파일되면, HTML 마크업과 C\# 렌더링 로직이 컴포넌트 클래스로 변환됩니다. 만들어지는 클래스의 이름은 파일의 이름과 같은 이름을 사용합니다.
12 |
13 | 컴포넌트 클래스의 멤버들은 `@functions` 블록에 정의됩니다. \(`@functions` 블록을 여러번 쓰는 것도 가능합니다.\) `@functions` 블록 안에서 컴포넌트의 상태 \(프로퍼티, 필드\)가 이벤트 처리를 위한 메서드나 다른 컴포넌트 로직을 위하여 추가될 수 있습니다.
14 |
15 | 그리고 컴포넌트 멤버는 `@` 으로 시작하는 C\# 표현식을 사용하는 컴포넌트의 렌더링 로직의 일부로서 사용할 수 있습니다. 예를 들어, 필드의 값을 렌더링하기 위하여 C\# 필드 이름 앞에 `@` 접두사를 붙여 사용할 수 있습니다. 다음과 같이 사용하면 값이 평가되고 렌더링됩니다.
16 |
17 | * CSS의 `font-style` 프로퍼티에 지정할 값으로 `_headingFontStyle` 변수 사용
18 | * `
` 요소의 내용으로 `_headingText` 변수 사용
19 |
20 | ```text
21 |
@_headingText
22 |
23 | @functions {
24 | private string _headingFontStyle = "italic";
25 | private string _headingText = "Put on your new Blazor!";
26 | }
27 | ```
28 |
29 | 컴포넌트가 처음 렌더링되면, 컴포넌트는 이벤트에 반응하여 렌더 트리를 다시 생성합니다. Blazor는 그 다음 새로 만들어진 트리와 기존의 트리를 비교하여 브라우저의 문서 개체 모델 \(DOM\)에 반영해야 할 변경 사항들을 적용합니다.
30 |
31 | ### 컴포넌트 사용하기
32 |
33 | 컴포넌트는 HTML 요소 문법을 사용하여 다른 컴포넌트를 포함할 수 있습니다. 컴포넌트를 사용하기 위한 마크업 문법은 HTML 태그처럼 보이지만 태그의 이름은 컴포넌트 형식의 이름을 사용합니다.
34 |
35 | 아래의 마크업은 `HeadingComponent` \(_HeadingComponent.cshtml_\) 인스턴스를 렌더링합니다:
36 |
37 | ```text
38 |
39 | ```
40 |
41 | ### 컴포넌트 매개 변수
42 |
43 | 컴포넌트는 `[Parameter]` 어트리뷰트가 적용된 컴포넌트 클래스 상의 _비 공개_ 프로퍼티로 정의되는 _컴포넌트 매개 변수_ 라는 것을 가질 수 있습니다. 이 어트리뷰트를 사용하여 컴포넌트 마크업에서 인자를 지정할 수 있게 합니다.
44 |
45 | 다음의 예제에서는, `ParentComponent`는 `ChildComponent`의 `Title` 프로퍼티에 값을 설정합니다.
46 |
47 | _ParentComponent.cshtml_:
48 |
49 | ```text
50 | @page "/ParentComponent"
51 |
52 |
Parent-child example
53 |
54 |
55 | Child content of the child component is supplied by the parent component.
56 |
57 | ```
58 |
59 | _ChildComponent.cshtml_:
60 |
61 | ```text
62 |
63 |
@Title
64 |
@ChildContent
65 |
66 |
67 | @functions {
68 | [Parameter]
69 | private string Title { get; set; }
70 |
71 | [Parameter]
72 | private RenderFragment ChildContent { get; set; }
73 | }
74 | ```
75 |
76 | ### 자식 콘텐츠
77 |
78 | 컴포넌트는 다른 컴포넌트의 내용을 설정할 수 있습니다. 할당하는 컴포넌트는 내용을 받는 컴포넌트를 가리키는 태그 사이에 들어갈 내용을 지정할 수 있습니다. 예를 들어, `ParentComponent` 는 `ChildComponent` 가 렌더링할 내용을 **<ChildComponent>** 태그 사이에 지정할 수 있습니다.
79 |
80 | _ParentComponent.cshtml_:
81 |
82 | ```text
83 | @page "/ParentComponent"
84 |
85 |
Parent-child example
86 |
87 |
88 | Child content of the child component is supplied by the parent component.
89 |
90 | ```
91 |
92 | 자식 컴포넌트는 [RenderFragment](https://blazor.net/api/Microsoft.AspNetCore.Blazor.RenderFragment.html)로 표현되는 `ChildContent` 프로퍼티를 가지고 있습니다. `ChildContent`의 내용은 자식 컴포넌트의 마크업에 들어있으며, 이 내용을 렌더링해야 합니다. 다음의 예제에서는, `ChildContent`의 내용을 부모 컴포넌트로부터 받아서, Bootstrap 패널의 `panel-body` 안에 렌더링합니다.
93 |
94 | _ChildComponent.cshtml_:
95 |
96 | ```text
97 |
98 |
@Title
99 |
@ChildContent
100 |
101 |
102 | @functions {
103 | [Parameter]
104 | private string Title { get; set; }
105 |
106 | [Parameter]
107 | private RenderFragment ChildContent { get; set; }
108 | }
109 | ```
110 |
111 | **노트**
112 |
113 | `RenderFragment` 콘텐츠를 받는 프로퍼티의 이름은 관례상 반드시 `ChildContent`로 지정해야 합니다.
114 |
115 | ### 데이터 바인딩
116 |
117 | 데이터 바인딩을 컴포넌트와 DOM 요소에 적용하기 위하여 `bind` 어트리뷰트를 사용할 수 있습니다. 다음의 예제는 `ItalicsCheck` 프로퍼티를 체크 박스의 체크 상태에 바인딩합니다.
118 |
119 | ```text
120 |
121 | ```
122 |
123 | 체크 박스가 선택되거나 선택되지 않았을 때, 프로퍼티의 값은 각각 `true`와 `false`로 수정됩니다.
124 |
125 | 체크 박스는 프로퍼티의 값 변경이 일어날 때가 아니라 컴포넌트가 렌더링 될 때만 UI에서 업데이트됩니다. 이벤트 처리기 코드가 실행 된 후에 컴포넌트가 렌더링되므로 대개 프로퍼티 업데이트는 UI에 즉시 반영됩니다.
126 |
127 | `bind` 어트리뷰트를 `CurrentValue` 프로퍼티 \(``\)에 사용하면 기본적으로 다음과 같은 의미가 됩니다:
128 |
129 | ```text
130 |
132 | ```
133 |
134 | 컴포넌트가 렌더링될 때, 텍스트 박스의 `value` 어트리뷰트의 값은 `CurrentValue` 프로퍼티로부터 옵니다. 사용자가 텍스트 박스 안에 글자를 입력하면, `onchange` 이벤트가 호출되어 `CurrentValue` 프로퍼티의 값이 바뀐 값으로 변경됩니다. 실제로 만들어지는 코드는 이보다 좀 더 복잡한데, `bind` 어트리뷰트가 몇몇 형식 변환을 처리하기 때문입니다. 원칙적으로, `bind` 어트리뷰트는 현재 표현식의 값을 `value` 어트리뷰트에 연관시키고, 등록된 처리기를 사용하여 변화를 관리합니다.
135 |
136 | **문자열 서식**
137 |
138 | [DateTime](https://docs.microsoft.com/dotnet/api/system.datetime)과 함께 데이터 바인딩을 하면 문자열로 형식화할 수 있습니다: \(단, 통화나 숫자 형식과 같은 형식은 현재 지원되지 않습니다.\)
139 |
140 | ```text
141 |
142 |
143 | @functions {
144 | [Parameter]
145 | private DateTime StartDate { get; set; } = new DateTime(2020, 1, 1);
146 | }
147 | ```
148 |
149 | `format-value` 어트리뷰트에는 `input` 요소의 `value` 어트리뷰트에 적용할 날짜 서식을 지정합니다. 서식은 또한 `onchange` 이벤트가 발생하였을 때 값을 해석하기 위해서도 사용됩니다.
150 |
151 | **컴포넌트 매개 변수**
152 |
153 | Binding은 또한 `bind-{property}`와 같이 사용하여, 컴포넌트에 걸쳐 프로퍼티 값을 바인딩 할 수 있는 컴포넌트 매개 변수를 인식합니다.
154 |
155 | 다음 컴포넌트는 `ChildComponent`라는 자식 컴포넌트를 사용하며, 부모 컴포넌트의 `ParentYear` 매개 변수를 자식 컴포넌트의 `Year` 매개 변수에 바인딩합니다.
156 |
157 | 부모 컴포넌트:
158 |
159 | ```text
160 | @page "/ParentComponent"
161 |
162 |
187 |
188 | @functions {
189 | [Parameter]
190 | private int Year { get; set; }
191 |
192 | [Parameter]
193 | private Action YearChanged { get; set; }
194 | }
195 | ```
196 |
197 | `Year` 매개 변수는 `Year` 매개 변수의 형식과 일치하는 `YearChanged` 라는 보조 이벤트를 가지고 있기 때문에 바인딩을 지원합니다.
198 |
199 | `ParentComponent`를 불러들이면 다음과 같은 마크업이 만들어지게 됩니다:
200 |
201 | ```text
202 |
Parent Component
203 |
204 |
ParentYear: 1978
205 |
206 |
Child Component
207 |
208 |
Year: 1978
209 | ```
210 |
211 | 만약 `ParentYear` 프로퍼티가 `ParentComponent` 안의 버튼을 클릭함으로서 값이 변경되면, `ChildComponent`의 `Year` 프로퍼티가 수정됩니다. `ParentComponent`가 렌더링될 때 새로운 값을 가진 `Year` 프로퍼티가 UI에 렌더링됩니다.
212 |
213 | ```text
214 |
Parent Component
215 |
216 |
ParentYear: 1986
217 |
218 |
Child Component
219 |
220 |
Year: 1986
221 | ```
222 |
223 | ### 이벤트 처리
224 |
225 | Blazor는 이벤트 처리 기능을 제공합니다. HTML 요소의 어트리뷰트 중 `on` \(예를 들어, `onclick`, `onsubmit` 같은\) 어트리뷰트에 대리자 형식의 값을 지정하여, Blazor가 어트리뷰트의 값을 이벤트 처리기로 취급합니다. 이런 어트리뷰트의 이름은 항상 `on`으로 시작합니다.
226 |
227 | 아래의 코드는 UI에서 버튼이 눌릴 때 마다 `UpdateHeading` 메서드를 호출합니다:
228 |
229 | ```text
230 |
233 |
234 | @functions {
235 | void UpdateHeading(UIMouseEventArgs e)
236 | {
237 | ...
238 | }
239 | }
240 | ```
241 |
242 | 아래의 코드는 UI에서 체크 박스의 선택 상태가 바뀔 때 마다 `CheckboxChanged` 메서드를 호출합니다:
243 |
244 | ```text
245 |
246 |
247 | @functions {
248 | void CheckboxChanged()
249 | {
250 | ...
251 | }
252 | }
253 | ```
254 |
255 | 이벤트 처리기는 또한 비동기 메서드로 정의될 수 있고, `Task` 를 반환할 수 있습니다. `StateHasChanged()` 같은 메서드를 호출할 필요가 없습니다. 예외가 발생할 경우 자동으로 기록됩니다.
256 |
257 | ```text
258 |
261 |
262 | @functions {
263 | async Task UpdateHeading(UIMouseEventArgs e)
264 | {
265 | ...
266 | }
267 | }
268 | ```
269 |
270 | 몇몇 이벤트의 경우, 특정 이벤트에 대한 상세 정보를 담은 인자 형식이 제공됩니다. 만약 이들 이벤트 형식을 이용할 필요가 없다면, 메서드 호출을 할 때에도 사용하지 않고 생략할 수 있습니다.
271 |
272 | 지원되는 이벤트 인자 형식들은 다음과 같습니다:
273 |
274 | * UIEventArgs
275 | * UIChangeEventArgs
276 | * UIKeyboardEventArgs
277 | * UIMouseEventArgs
278 |
279 | 람다 표현식도 사용할 수 있습니다:
280 |
281 | ```text
282 |
283 | ```
284 |
285 | ### 컴포넌트의 참조 가져오기
286 |
287 | 컴포넌트 참조를 통하여 컴포넌트 인스턴스에 대한 참조를 얻어 인스턴스에 대해 `Show`나 `Reset` 같은 명령을 내릴 수 있습니다. 컴포넌트의 참조를 얻으려면, 자식 컴포넌트에 `ref` 어트리뷰트를 추가하고, 자식 컴포넌트와 동일한 타입을 가진, `ref` 어트리뷰트에 지정했던 이름과 같은 이름의 필드를 정의합니다.
288 |
289 | ```text
290 |
291 |
292 | @functions {
293 | MyLoginDialog loginDialog;
294 |
295 | void OnSomething()
296 | {
297 | loginDialog.Show();
298 | }
299 | }
300 | ```
301 |
302 | 컴포넌트가 렌더링되면, `loginDialog` 필드가 `MyLoginDialog` 자식 컴포넌트 인스턴스의 참조를 가리키게 됩니다. 이제 컴포넌트 인스턴스에 대해 .NET 메서드를 호출할 수 있습니다.
303 |
304 | **중요**
305 |
306 | `loginDialog` 변수는 컴포넌트가 렌더링 된 후에만 참조가 할당되고, 그 결과는 참조 할 것이 없기 때문에 `MyLoginDialog` 요소를 포함합니다. 컴포넌트의 렌더링이 끝난 후 컴포넌트의 참조를 다루기 위해서는, `OnAfterRenderAsync` 또는 `OnAfterRender` 라이프사이클 메서드를 사용해야 합니다.
307 |
308 | 구성 요소 참조를 캡처하는 동안 [요소 참조 캡처] (https://blazor.net/docs/javascript-interop.html#capture-references-to-elements)와 유사한 구문을 사용하지만, 이것은 [JavaScript 연동](https://blazor.net/docs/javascript-interop.html) 기능을 사용하는 것이 아닙니다. 구성 요소 참조는 JavaScript 코드로 전달되지 않습니다. .NET 코드에서만 사용됩니다.
309 |
310 | **노트**
311 |
312 | 컴포넌트 참조를 자식 컴포넌트의 상태를 바꾸기 위해서 **사용하면 안됩니다.** 대신, 항상 보통의 선언적 매개 변수를 사용하여 자식 컴포넌트로 데이터를 전달하도록 합니다. 이렇게 하면 렌더러에 의하여 자식 컴포넌트가 정확한 시점에 렌더링됩니다.
313 |
314 | ### 라이프사이클 메서드
315 |
316 | `OnInitAsync`과 `OnInit` 메서드는 컴포넌트가 초기화된 이후에 호출되는 메서드입니다. 비동기 작업을 수행하기 위해서는, `OnInitAsync`와 `await` 키워드를 다음과 같이 사용합니다:
317 |
318 | ```text
319 | protected override async Task OnInitAsync()
320 | {
321 | await ...
322 | }
323 | ```
324 |
325 | 동기 방식으로 작업을 수행하기 위해서는, `OnInit`을 다음과 같이 사용합니다:
326 |
327 | ```text
328 | protected override void OnInit()
329 | {
330 | ...
331 | }
332 | ```
333 |
334 | `OnParametersSetAsync`와 `OnParametersSet` 메서드는 컴포넌트가 부모 컴포넌트로부터 매개 변수의 값을 받았고, 그 값이 프로퍼티에 설정되었을 때 실행됩니다. 이들 메서드는 컴포넌트 초기화 중에 `OnInit` 메서드 다음에 실행됩니다.
335 |
336 | ```text
337 | protected override async Task OnParametersSetAsync()
338 | {
339 | await ...
340 | }
341 | ```
342 |
343 | ```text
344 | protected override void OnParametersSet()
345 | {
346 | ...
347 | }
348 | ```
349 |
350 | `OnAfterRenderAsync`와 `OnAfterRender` 메서드는 컴포넌트의 렌더링이 끝날 때 마다 호출됩니다. 요소와 컴포넌트 참조가 이 시점부터 사용 가능해집니다. 이 단계에서 렌더링된 콘텐츠에 대한 추가 작업을 진행할 수 있는데, 예를 들면 렌더링된 DOM 요소에 대해 서드파티 자바스크립트 라이브러리를 호출할 수 있습니다.
351 |
352 | ```text
353 | protected override async Task OnAfterRenderAsync()
354 | {
355 | await ...
356 | }
357 | ```
358 |
359 | ```text
360 | protected override void OnAfterRender()
361 | {
362 | ...
363 | }
364 | ```
365 |
366 | `SetParameters`는 매개 변수들이 설정되기 전에 호출될 내용으로 재정의할 수 있습니다:
367 |
368 | ```text
369 | public override void SetParameters(ParameterCollection parameters)
370 | {
371 | ...
372 |
373 | base.SetParameters(parameters);
374 | }
375 | ```
376 |
377 | 만약 `base.SetParameters`가 호출되지 않으면, 커스텀 코드는 필요한 모든 방식으로 들어오는 매개 변수 값을 해석 할 수 있습니다. 예를 들어 들어오는 매개 변수를 클래스의 프로퍼티에 할당 할 필요는 없습니다.
378 |
379 | `ShouldRender`는 UI가 새로 고쳐지는 것을 방지하기 위해 재정의할 수 있습니다. 메서드에서 `true`를 반환하면 UI가 새로 고쳐집니다. `ShouldRender`가 재정의 되었더라도 항상 최초 한 번 컴포넌트가 렌더링됩니다.
380 |
381 | ```text
382 | protected override bool ShouldRender()
383 | {
384 | var renderUI = true;
385 |
386 | return renderUI;
387 | }
388 | ```
389 |
390 | ### IDisposable로 컴포넌트 할당 해제하기
391 |
392 | 만약 컴포넌트가 [IDisposable](https://docs.microsoft.com/dotnet/api/system.idisposable) 인터페이스를 구현했다면, UI에서 컴포넌트가 제거될 때에 [Dispose 메서드](https://docs.microsoft.com/dotnet/standard/garbage-collection/implementing-dispose)가 호출됩니다. 아래 컴포넌트는 `@implements IDisposable` 지시자와 `Dispose` 메서드를 사용하는 예시입니다:
393 |
394 | ```text
395 | @using System
396 | @implements IDisposable
397 |
398 | ...
399 |
400 | @functions {
401 | public void Dispose()
402 | {
403 | ...
404 | }
405 | }
406 | ```
407 |
408 | ### 라우팅
409 |
410 | Blazor에서 라우팅은 앱 안에서 접근 가능한 각각의 컴포넌트마다 라우팅 템플릿을 지정하는 것으로 달성할 수 있습니다.
411 |
412 | _\*.cshtml_ 파일을 `@page` 지시자와 함께 컴파일하면, 만들어지는 클래스에 [RouteAttribute](https://docs.microsoft.com/dotnet/api/microsoft.aspnetcore.mvc.routeattribute)가 추가됩니다. 런타임에서는, 라우터가 `RouteAttribute`가 첨부된 컴포넌트 클래스들을 찾고, 요청한 URL과 일치하는 라우팅 템플릿을 가진 컴포넌트를 렌더링하게 됩니다.
413 |
414 | 여러 개의 라우팅 템플릿을 컴포넌트에 적용할 수 있습니다. 아래의 컴포넌트는 `/Blazorroute`와 `/DifferentBlazorRoute` 경로에 대한 요청이 있을 때 작동하게 됩니다:
415 |
416 | ```text
417 | @page "/BlazorRoute"
418 | @page "/DifferentBlazorRoute"
419 |
420 |
Blazor routing
421 | ```
422 |
423 | ### 라우팅 매개 변수
424 |
425 | Blazor 컴포넌트는 라우팅 매개 변수를 `@page` 지시자로 지정한 라우팅 템플릿으로부터 받을 수 있습니다. Blazor의 클라이언트 측 라우터는 라우팅 매개 변수를 사용하여 적절한 컴포넌트 매개 변수를 획득합니다.
426 |
427 | _RouteParameter.cshtml_:
428 |
429 | ```text
430 | @page "/RouteParameter"
431 | @page "/RouteParameter/{text}"
432 |
433 |
Blazor is @Text!
434 |
435 | @functions {
436 | [Parameter]
437 | private string Text { get; set; } = "fantastic";
438 | }
439 | ```
440 |
441 | 매개 변수를 생략하는 것은 지원되지 않으며, 그래서 2개의 `@page` 지시자를 예제에서 지정한 것입니다. 처음 사용한 지시자는 매개 변수를 지정하지 않았을 때에도 컴포넌트에 대한 탐색을 허용하기 위함이며, 두 번째 `@page` 지시자는 `{text}` 라우팅 파라미터를 받아, 컴포넌트의 `Text` 프로퍼티에 값을 할당하기 위하여 사용되었습니다.
442 |
443 | ### "코드 비하인드" 방식으로 기본 클래스 상속하기
444 |
445 | Blazor 컴포넌트 파일 \(_\*.cshtml_\)은 HTML 마크업와 C\# 코드를 하나의 파일 안에 담고 있습니다. `@inherits` 지시자는 Blazor에서 컴포넌트 마크업와 코드를 분리하는 "코드 비하인드" 방식의 프로그래밍 기법을 사용할 수 있게 해줍니다.
446 |
447 | 이 [예제 앱](https://github.com/aspnet/Blazor.Docs/tree/master/docs/common/samples/)에서는 컴포넌트가 어떻게 `BlazorRocksBase` 라는 클래스를 상속받아서 컴포넌트의 프로퍼티과 메서드를 제공하는지 방법을 보여줍니다.
448 |
449 | _BlazorRocks.cshtml_:
450 |
451 | ```text
452 | @page "/BlazorRocks"
453 | @*
454 | The inherit directive provides the properties and methods
455 | of the BlazorRocksBase class to this component.
456 | *@
457 | @inherits BlazorRocksBase
458 |
459 |
@BlazorRocksText
460 | ```
461 |
462 | _BlazorRocksBase.cs_:
463 |
464 | ```text
465 | using Microsoft.AspNetCore.Blazor.Components;
466 |
467 | public class BlazorRocksBase : BlazorComponent
468 | {
469 | public string BlazorRocksText { get; set; } = "Blazor rocks the browser!";
470 | }
471 | ```
472 |
473 | 상속의 대상이 되는 기본 클래스는 반드시 [BlazorComponent](https://blazor.net/api/Microsoft.AspNetCore.Blazor.Components.BlazorComponent.html) 클래스에서 상속받아야 합니다.
474 |
475 | ### Razor 지원
476 |
477 | **Razor 지시자**
478 |
479 | 아래 표에 나와있는 Razor 지시자들을 Blazor 앱에서 사용할 수 있습니다.
480 |
481 | | 지시자 | 설명 |
482 | | :--- | :--- |
483 | | [@functions](https://docs.microsoft.com/aspnet/core/mvc/views/razor#functions) | C\# 코드 블록을 컴포넌트에 추가합니다. |
484 | | `@implements` | 만들어지는 컴포넌트 클래스가 구현할 인터페이스를 지정합니다. |
485 | | [@inherits](https://docs.microsoft.com/aspnet/core/mvc/views/razor#inherits) | 구성 요소가 상속하는 클래스를 완벽하게 제어합니다. |
486 | | [@inject](https://docs.microsoft.com/aspnet/core/mvc/views/razor#inject) | [서비스 컨테이너](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection)로 부터 서비스 주입이 가능하게 합니다. 자세한 내용은, [뷰에 의존성 주입하기](https://docs.microsoft.com/aspnet/core/mvc/views/dependency-injection) 문서를 참고하세요. |
487 | | `@layout` | 레이아웃 컴포넌트를 지정합니다. 레이아웃 컴포넌트는 코드 중복과 비 일관성을 방지하기 위하여 사용합니다. |
488 | | [@page](https://docs.microsoft.com/aspnet/core/mvc/razor-pages#razor-pages) | 컴포넌트가 요청을 직접 처리해야 할 지의 여부를 지정합니다. `@page` 지시자는 라우팅 경로와 선택적 매개 변수와 함께 지정할 수 있습니다. Razor 페이지와는 달리, `@page` 지시자는 파일의 맨 처음이 아닌 곳에 등장해도 됩니다. 자세한 내용은, [라우팅](https://blazor.net/docs/routing.html) 문서를 참고하세요. |
489 | | [@using](https://docs.microsoft.com/aspnet/core/mvc/views/razor#using) | C\#의 `using` 지시자를 생성되는 컴포넌트 클래스 코드에 추가합니다. |
490 | | [@addTagHelper](https://docs.microsoft.com/aspnet/core/mvc/views/razor#tag-helpers) | `@addTagHelper` 지시자를 사용하여 앱의 어셈블리가 아닌 다른 어셈블리의 컴포넌트를 사용할 수 있습니다. |
491 |
492 | **조건부 어트리뷰트**
493 |
494 | Blazor는 .NET의 값을 기초로 어트리뷰트의 렌더링 여부를 선택적으로 처리할 수 있습니다. 만약 값이 `false` 또는 `null`인 경우, Blazor는 어트리뷰트 렌더링을 생략합니다. 만약 값이 `true`이면, 프로퍼티는 값이 지정되지 않은 상태로 렌더링됩니다.
495 |
496 | 다음 예제에서, `IsCompleted`는 `checked` 어트리뷰트가 컨트롤의 마크업에 렌더링될 지 여부를 결정합니다.
497 |
498 | ```text
499 |
500 |
501 | @functions {
502 | [Parameter]
503 | private bool IsCompleted { get; set; }
504 | }
505 | ```
506 |
507 | 만약 `IsCompleted`가 `true`이면, 체크박스는 다음과 같이 렌더링됩니다:
508 |
509 | ```text
510 |
511 | ```
512 |
513 | 만약 `IsCompleted`가 `false`이면, 체크박스는 다음과 같이 렌더링됩니다:
514 |
515 | ```text
516 |
517 | ```
518 |
519 | **Razor에 대한 더 자세한 내용**
520 |
521 | Razor에 대한 더 자세한 내용을 알고 싶다면, [Razor 문법 레퍼런스](https://docs.microsoft.com/aspnet/core/mvc/views/razor) 문서를 참고하세요. 참고할 것은, 이 문서에서 설명하는 Razor의 기능들 중 Blazor에서 아직 지원하지 않는 것이 있을 수 있습니다.
522 |
523 | ### HTML 직접 사용
524 |
525 | Blazor는 보통 DOM의 텍스트 노드에 들어갈 텍스트를 렌더링하는데, 이는 텍스트에 마크업이 사용되더라도 마크업이 아닌 일반 텍스트로 취급됨을 의미합니다. HTML 그 자체를 렌더링하기 위해서는, HTML 콘텐츠를 `MarkupString` 형식의 값으로 포장하여, DOM에 HTML이나 SVG 그 자체로 해석하여 추가되도록 해야 합니다.
526 |
527 | **경고**
528 |
529 | 신뢰할 수 없는 출처에서 만들어진 HTML을 직접 추가하는 것은 **보안 위험 요소**가 될 수 있으며, 반드시 피해야 합니다!
530 |
531 | 다음의 예제에서는 `MarkupString` 형식을 사용하여 컴포넌트의 출력 결과에 정적 HTML 콘텐츠 블록을 추가하는 방법을 보여줍니다:
532 |
533 | ```text
534 | @((MarkupString)myMarkup)
535 |
536 | @functions {
537 | string myMarkup = "
This is a markup string.
";
538 | }
539 | ```
540 |
541 | ### 템플릿 컴포넌트
542 |
543 | 템플릿 컴포넌트는 하나 이상의 UI 템플릿을 매개 변수로서 받아들이는 컴포넌트이며, 컴포넌트의 렌더링 로직의 일부로서 사용할 수 있습니다. 템플릿 컴포넌트는 보통의 컴포넌트보다 더 재사용성이 좋은 높은 수준의 컴포넌트를 만들 수 있게 해줍니다. 다음은 몇 가지 예시입니다:
544 |
545 | * 테이블의 머리글, 본문, 바닥글을 커스터마이징할 수 있는 테이블 컴포넌트.
546 | * 사용자가 리스트의 렌더링 항목을 직접 지정할 수 있는 리스트 컴포넌트.
547 |
548 | #### 템플릿 매개 변수
549 |
550 | 템플릿 컴포넌트는 하나 이상의 `RenderFragment`나 `RenderFragment` 타입의 매개 변수를 지정할 수 있도록 정의된 컴포넌트입니다. 렌더링 조각은 컴포넌트에 의하여 렌더링될 UI 조각을 나타냅니다. 렌더링 조각은 선택적으로 렌더링 조각이 호출될 때 지정할 수 있는 매개 변수를 받습니다.
551 |
552 | _Components/TableTemplate.cshtml_:
553 |
554 | ```text
555 | @typeparam TItem
556 |
557 |
571 |
572 | @functions {
573 | [Parameter] RenderFragment TableHeader { get; set; }
574 | [Parameter] RenderFragment RowTemplate { get; set; }
575 | [Parameter] RenderFragment TableFooter { get; set; }
576 | [Parameter] IReadOnlyList Items { get; set; }
577 | }
578 | ```
579 |
580 | 템플릿 구성 요소를 사용하는 경우 템플릿 매개 변수는 매개 변수 \(아래 예제의 `TableHeader` 및 `RowTemplate`\)의 이름과 일치하는 하위 요소를 사용하여 지정할 수 있습니다.
581 |
582 | ```text
583 |
584 |
585 |
ID
586 |
Name
587 |
588 |
589 |
@context.PetId
590 |
@context.Name
591 |
592 |
593 | ```
594 |
595 | #### 템플릿 컨텍스트 매개 변수
596 |
597 | 요소로 전달된 `RenderFragment` 형식의 컴포넌트 매개 변수는 `context` 라는 이름의 암시적 매개 변수로 사용할 수 있지만 \(앞의 코드 샘플의 예시에서는 `@context.PetId` 였습니다.\), 자식 요소의 `Context` 어트리뷰트을 사용하여 매개 변수 이름을 바꿀 수 있습니다. 다음 예제에서 `RowTemplate` 요소의 `Context` 어트리뷰트에서 `pet`으로 매개 변수의 이름을 지정하는 방법을 보여줍니다.
598 |
599 | ```text
600 |
601 |
602 |
ID
603 |
Name
604 |
605 |
606 |
@pet.PetId
607 |
@pet.Name
608 |
609 |
610 | ```
611 |
612 | 또는 `Context` 어트리뷰트를 컴포넌트 요소에 지정할 수도 있습니다. `Context` 어트리뷰트에 지정한 이름은 모든 템플릿 파라미터에 영향을 줍니다. 이 방법은 암시적으로 하위 콘텐츠에 대한 매개 변수 이름을 지정하려는 경우에 유용할 수 있습니다. \(하위 요소를 감싸거나 할 필요가 없습니다.\) 다음 예제에서는, `Context` 어트리뷰트가 `TableTemplate` 요소에 나타나고, 모든 템플릿 파라미터의 이름이 지정된 이름으로 변경됩니다:
613 |
614 | ```text
615 |
616 |
617 |
ID
618 |
Name
619 |
620 |
621 |
@pet.PetId
622 |
@pet.Name
623 |
624 |
625 | ```
626 |
627 | #### 제네릭 형식의 컴포넌트
628 |
629 | 템플릿화된 컴포넌트는 보통 제네릭 형식으로 만들어집니다. 예를 들어, 제네릭 ListView 컴포넌트는 `IEnumerable` 의 값을 렌더링하기 위하여 사용될 수 있습니다. 제네릭 컴포넌트를 정의하기 위해서는, `@typeparam` 지시자를 매개 변수에 지정해야 합니다.
630 |
631 | _Components/ListViewTemplate.cshtml_:
632 |
633 | ```text
634 | @typeparam TItem
635 |
636 |
655 |
656 |
657 | ```
658 |
659 | 그렇지 않으면, 형식 매개 변수의 이름과 같은 어트리뷰트에 형식 이름을 반드시 지정해야 합니다. 다음의 예시에서는, `TItem="Pet"`으로 형식을 지정하고 있습니다:
660 |
661 | ```text
662 |
663 |
664 |
@pet.Name
665 |
666 |
667 | ```
668 |
669 | ### Razor 템플릿
670 |
671 | 렌더링 조각은 Razor 템플릿 문법을 사용하여 정의할 수 있습니다. Razor 템플릿은 UI 조각을 정의하기 위한 하나의 방법이고, 다음과 같은 형식을 따릅니다:
672 |
673 | ```text
674 | @...
675 | ```
676 |
677 | 다음의 예제에서는 어떻게 `RenderFragment`와 `RenderFragment`의 값을 지정하는지 보여줍니다.
678 |
679 | _RazorTemplates.cshtml_:
680 |
681 | ```text
682 | @{
683 | RenderFragment template = @
The time is @DateTime.Now.
;
684 | RenderFragment petTemplate = (pet) => @
Your pet's name is @pet.Name.
;
685 | }
686 | ```
687 |
688 | Razor 템플릿을 사용하여 정의되는 렌더링 조각은 템플릿화된 컴포넌트의 인자로 전달되거나 그 자체로 렌더링될 수 있습니다. 예를 들어, 앞의 템플릿은 다음과 같은 Razor 마크업으로 직접 렌더링될 수 있습니다:
689 |
690 | ```text
691 | @template
692 |
693 | @petTemplate(new Pet { Name = "Rex" })
694 | ```
695 |
696 | 렌더링된 결과:
697 |
698 | ```text
699 | The time is 10/04/2018 01:26:52.
700 |
701 | Your pet's name is Rex.
702 | ```
703 |
704 |
--------------------------------------------------------------------------------
/debugging.md:
--------------------------------------------------------------------------------
1 | # 디버깅
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | Blazor는 Chrome에서 WebAssembly로 실행되는 클라이언트 측 Blazor 앱에 대한 _매우 초기 단계의_ 디버깅을 일부 지원합니다. 매우 제한적이고 다듬어지지 않은 초창기 수준의 디버깅 지원이지만, 기본적인 디버깅 인프라가 같이 개발되고 있습니다.
6 |
7 | Chrome에서 클라이언트 측 Blazor 앱을 디버깅하려면:
8 |
9 | * `Debug` 빌드 구성 \(게시되지 않은 앱의 기본 구성\)으로 Blazor 앱을 빌드합니다.
10 | * Blazor 앱을 Chrome에서 실행합니다.
11 | * 앱에 키보드 포커스를 둔 상태에서 \(개발자 도구 패널이 아닙니다. 햇갈리지 않도록 개발자 도구 패널은 닫으시는 것을 권합니다.\), 다음의 Blazor 디버깅 전용 키보드 단축 키를 누릅니다:
12 | * Windows와 Linux에서는 `Shift+Alt+D` 키를 누릅니다.
13 | * macOS에서는 `Shift+Cmd+D` 키를 누릅니다.
14 |
15 | Blazor 앱을 디버깅하려면 Chrome을 원격 디버깅을 활성화한 상태에서 실행합니다. 만약 원격 디버깅이 비활성화되어있으면, Chrome이 오류 페이지를 생성합니다. 오류 페이지에는 Chrome이 디버깅 포트를 연 상태에서 실행하도록 하기 위한 방법이 포함되어있으며, 이를 통해 Blazor 디버깅 프록시가 앱에 연결할 수 있습니다. 안내되어있는대로 _모든 Chrome 인스턴스들을 닫은 후_ Chrome을 다시 시작합니다.
16 |
17 | 
18 |
19 | 원격 디버깅을 활성화한 상태에서 Chrome을 실행하면, 디버깅 키보드 단축키가 새로운 디버거 탭을 엽니다. 잠시 후, _Sources_ 탭에는 앱이 사용하는 모든 .NET 어셈블리들의 목록이 표시됩니다. 각 어셈블리를 열어, 사용 가능한 _.cs_\|_.cshtml_ 소스 파일들 중 디버깅하려는 파일을 찾습니다. 중단점을 설정하고, 앱의 탭으로 되돌아와서 중단점을 설정해둔 부분까지 실행합니다. 중단점을 만나면, 한 단계씩 실행 \(`F10`\) 하거나, 정상적으로 계속 실행 \(`F8`\) 합니다.
20 |
21 | 
22 |
23 | Blazor는 [Chrome DevTools 프로토콜](https://chromedevtools.github.io/devtools-protocol/)을 구현하는, .NET에 특화된 정보를 적절하게 융합하는 디버깅 프록시를 제공합니다. 디버깅 키보드 단축키가 눌러지면 Blazor는 Chrome DevTools를 프록시에서 가리킵니다. 프록시는 디버그하고자하는 브라우저 창에 연결합니다. \(따라서 원격 디버깅을 활성화해야합니다.\)
24 |
25 | 그런데 브라우저 소스 맵을 사용하지 않는 이유가 궁금하실 것입니다. 소스 맵은 브라우저가 컴파일된 파일과 원본 소스 파일 간의 관계를 알 수 있도록 해줍니다. 하지만, Blazor는 C\#과 JS/WASM과 직접 맵핑하는 것을 \(아직까지는\) 지원하지 않습니다. 대신, Blazor는 IL 해석을 브라우저 내에서 처리하므로, 소스 맵과는 관계가 없습니다.
26 |
27 | 또한 디버거 기능은 **매우 제한적**입니다. 다음의 기능만을 사용할 수 있습니다:
28 |
29 | * 실행 중인 메서드 안에서 한 단계씩 진행 \(`F10`\) 또는 계속 실행 \(`F8`\)하기
30 | * _로컬 변수_ 디스플레이에서, `int`, `string`, 그리고 `bool` 형식의 변수에 대한 값 보기
31 | * JavaScript에서 .NET으로 향하거나, .NET에서 JavaScript로 향하는 호출 과정을 포함하는 호출 스택 보기
32 |
33 | _할 수 없는 일_ 들은 다음과 같습니다:
34 |
35 | * 자식 메서드로 진입하여 실행하기 \(`F11`\)
36 | * `int`, `string`, 또는 `bool` 형식이 아닌 다른 모든 형식의 로컬 변수 값 보기
37 | * 클래스 속성이나 필드의 값 보기
38 | * 값을 보기 위하여 변수 위로 마우스 커서 가져가기
39 | * 콘솔에서 식 평가하기
40 | * 비동기 호출 간 전환하기
41 | * 보통의 디버깅 시나리오에서 지원하는 대부분의 기능들
42 |
43 | 더 많은 디버깅 시나리오의 개발은 엔지니어링 팀이 현재 계속 작업하고 있습니다.
44 |
45 | ## 문제 해결 팁
46 |
47 | 만약 오류가 발생하는 경우, 아래 내용이 도움이 될 수 있습니다:
48 |
49 | **디버거** 탭에서, 브라우저의 개발자 도구를 엽니다. 콘솔에서, `localStorage.clear()` 를 실행하여 모든 중단점을 제거합니다.
50 |
51 |
--------------------------------------------------------------------------------
/dependency-injection.md:
--------------------------------------------------------------------------------
1 | # 의존성 주입
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | Blazor는 [의존성 주입\(DI\)](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection) 를 기본으로 제공합니다. 앱에서는 내장된 서비스를 사용하여 컴포넌트로 의존성을 주입할 수 있습니다. 또한 커스텀 서비스를 정의하고, DI를 통해서 사용할 수도 있습니다.
6 |
7 | ### 의존성 주입이란?
8 |
9 | 의존성 주입은 서비스에 접근하기 위한 구성을 한 곳에서 관리하기 위한 기법입니다. 이 방법은 다음과 같은 장점이 있습니다:
10 |
11 | * 서비스 클래스의 단일 인스턴스를 여러 컴포넌트에 걸쳐 공유할 수 있습니다. \(싱글톤 서비스라고도 합니다.\)
12 | * 특정 서비스 클래스에서 컴포넌트를 분리하고, 추상화된 내용만을 참조할 수 있습니다. 예를 들어, `IDataAccess` 인터페이스는 `DataAccess` 라는 구체화된 클래스에 의하여 구현되는 상황을 가정할 수 있습니다. 컴포넌트가 DI를 사용하여 `IDataAccess` 인터페이스에 대한 구현체를 받기로 했다면, 컴포넌트는 이 인터페이스를 실제로 구현하는 클래스와는 결합되지 않습니다. 구현체는 교체될 수 있는데, 예를 들어 단위 테스트를 위한 모형의 구현체로 교체할 수 있습니다.
13 |
14 | Blazor의 의존성 주입 시스템은 컴포넌트들로 서비스 인스턴스들을 제공하는 역할을 합니다. 의존성 주입은 또한 의존성을 재귀적으로 처리하므로 서비스가 다른 서비스들을 참조하는 것도 가능합니다. 의존성 주입은 앱이 시작될 때 구성됩니다. 이 토픽의 후반부에서 예제를 다루겠습니다.
15 |
16 | ### 의존성 주입에 서비스 추가하기
17 |
18 | 새로운 앱을 만든 후에, `Startup.ConfigureServices` 메서드를 살펴봅니다:
19 |
20 | ```text
21 | public void ConfigureServices(IServiceCollection services)
22 | {
23 | // 여기에 커스텀 서비스를 추가합니다.
24 | }
25 | ```
26 |
27 | `ConfigureServices` 메서드로 [IServiceCollection](https://docs.microsoft.com/dotnet/api/microsoft.extensions.dependencyinjection.iservicecollection) 인스턴스가 전달되는데, 이것은 서비스 디스크립터 개체인 \([ServiceDescriptor](https://docs.microsoft.com/dotnet/api/microsoft.extensions.dependencyinjection.servicedescriptor)\) 형식의 인스턴스들의 목록입니다. 서비스는 서비스 디스크립터를 서비스 컬렉션에 추가함으로서 의존성 주입에 추가될 수 있습니다. 다음의 코드 예제는 이러한 컨셉을 설명합니다:
28 |
29 | ```text
30 | public void ConfigureServices(IServiceCollection services)
31 | {
32 | services.AddSingleton();
33 | }
34 | ```
35 |
36 | 서비스는 다음과 같이 생명 주기를 설정할 수 있습니다:
37 |
38 | | 생명 주기 | 설명 |
39 | | :--- | :--- |
40 | | [Singleton](https://docs.microsoft.com/dotnet/api/microsoft.extensions.dependencyinjection.servicedescriptor.singleton#Microsoft_Extensions_DependencyInjection_ServiceDescriptor_Singleton__1_System_Func_System_IServiceProvider___0__) | 의존성 주입에 의하여 서비스의 _싱글턴 인스턴스_ 가 생성됩니다. 이렇게 정의된 서비스를 필요로 하는 컴포넌트에 인스턴스가 전달됩니다. |
41 | | [Transient](https://docs.microsoft.com/dotnet/api/microsoft.extensions.dependencyinjection.servicedescriptor.transient) | 서비스에서 컴포넌트를 필요로 할 때 마다, 서비스의 _새로운 인스턴스_ 를 생성하여 전달합니다. |
42 | | [Scoped](https://docs.microsoft.com/dotnet/api/microsoft.extensions.dependencyinjection.servicedescriptor.scoped) | Blazor는 현재 의존성 주입의 범위를 지정하는 기능을 제공하지 않습니다. `Scoped`는 `Singleton`처럼 작동하므로, `Scoped` 대신 `Singleton`을 사용하는 것이 좋습니다. |
43 |
44 | Blazor의 의존성 주입 시스템은 ASP.NET Core의 의존성 주입 시스템을 기반으로 합니다. 더 자세한 정보는, [ASP.NET Core의 의존성 주입](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection)을 참고하십시오.
45 |
46 | ### 기본 서비스
47 |
48 | Blazor는 앱의 서비스 컬렉션에 자동으로 기본 서비스들을 추가하여 제공합니다. 다음의 표에서는 현재 Blazor의 [BrowserServiceProvider](https://blazor.net/api/Microsoft.AspNetCore.Blazor.Browser.Services.BrowserServiceProvider.html)에 의하여 제공되는 기본 서비스들을 나타내고 있습니다.
49 |
50 | | 서비스 | 설명 |
51 | | :--- | :--- |
52 | | [IUriHelper](https://blazor.net/api/Microsoft.AspNetCore.Blazor.Services.IUriHelper.html) | URI와 탐색 상태를 제어하는 도우미 서비스입니다. \(싱글턴\). |
53 | | [HttpClient](https://docs.microsoft.com/dotnet/api/system.net.http.httpclient) | URI로 식별되는 리소스에 대해 HTTP 요청을 보내거나 HTTP 응답을 받을 수 있는 수단을 제공합니다. \(싱글턴\) 참고할 것은, `HttpClient` 형식의 인스턴스는 브라우저를 사용하여 HTTP 요청을 백그라운드에서 처리합니다. [HttpClient.BaseAddress](https://docs.microsoft.com/dotnet/api/system.net.http.httpclient.baseaddress) 속성은 자동으로 앱의 기본 URI로 설정됩니다. |
54 |
55 | 커스텀 서비스 공급자를 `BrowserServiceProvider` 대신 사용하는 것도 가능합니다. 커스텀 서비스 공급자를 사용하면 앞의 표에서 제공되는 서비스가 포함되지 않기 때문에, 직접 해당 서비스들을 명시적으로 제공해야 합니다.
56 |
57 | ### 컴포넌트에서 서비스 요청하기
58 |
59 | 서비스 컬렉션에 서비스가 추가되면, 컴포넌트의 Razor 템플릿에 `@inject` Razor 지시자를 사용하여 주입할 수 있습니다. `@inject`는 두 개의 매개 변수를 받습니다:
60 |
61 | * 형식 이름: 주입하려는 서비스의 형식입니다.
62 | * 프로퍼티 이름: 주입되는 앱 서비스를 받을 속성의 이름을 지정합니다. 프로퍼티를 직접 만들 필요는 없고, 컴파일러가 대신 속성을 새로 정의합니다.
63 |
64 | 여러 개의 `@inject` 문을 사용하여 여러 달느 서비스들을 주입할 수도 있습니다.
65 |
66 | 다음의 예제에서는 `@inject`를 어떻게 사용하는지 보여줍니다. `Services.IDataAccess`를 구현하는 서비스를 컴포넌트의 `DataRepository` 속성에 주입합니다. 여기서 코드는 `IDataAccess`가 제공하는 추상화된 부분만을 사용한다는 것에 주목합니다:
67 |
68 | ```text
69 | @page "/customer-list"
70 | @using Services
71 | @inject IDataAccess DataRepository
72 |
73 |
82 |
83 | @functions {
84 | private IReadOnlyList Customers;
85 |
86 | protected override async Task OnInitAsync()
87 | {
88 | // The property DataRepository received an implementation
89 | // of IDataAccess through dependency injection. Use
90 | // DataRepository to obtain data from the server.
91 | Customers = await DataRepository.GetAllCustomersAsync();
92 | }
93 | }
94 | ```
95 |
96 | 내부적으로, 생성된 프로퍼티 \(`DataRepository`\)는 [InjectAttribute](https://blazor.net/api/Microsoft.AspNetCore.Blazor.Components.InjectAttribute.html) 어트리뷰트가 붙습니다. 보통 이 어트리뷰트는 직접 사용되지 않습니다. 구성 요소에 기본 클래스가 필요하고 주입된 속성이 기본 클래스에도 필요하면 `InjectAttribute`를 수동으로 추가 할 수 있습니다:
97 |
98 | ```text
99 | public class ComponentBase : BlazorComponent
100 | {
101 | // 컴포넌트의 기본 클래스에 InjectAttribute를 사용하더라도
102 | // Blazor의 의존성 주입이 적용됩니다.
103 | [Inject]
104 | protected IDataAccess DataRepository { get; set; }
105 | ...
106 | }
107 | ```
108 |
109 | 기본 클래스로부터 컴포넌트가 상속되면, `@inject` 지시자가 필요하지 않습니다. 기본 클래스에 `InjectAttribute`를 사용하는 것만으로도 충분합니다:
110 |
111 | ```text
112 | @page "/demo"
113 | @inherits ComponentBase
114 |
115 |
...
116 | ...
117 | ```
118 |
119 | ### 서비스로 의존성 주입
120 |
121 | 복잡한 서비스의 경우 더 많은 서비스들을 필요로 할 수 있습니다. 앞의 예시인 `DataAccess` 서비스는 Blazor의 기본 서비스인 `HttpClient`를 필요로 할 수 있습니다. `@inject` 또는 `InjectAttribute`를 서비스 안에서 사용할 수 없습니다. 이 경우 _생성자 주입_ 이 대신 사용되어야 합니다. 필요한 서비스들을 서비스의 생성자의 매개 변수에 추가하는 방법으로 지정할 수 있습니다. 의존성 주입에 의하여 서비스가 만들어지면, 생성자에서 필요로하는 서비스들을 인식하여 적절하게 제공합니다.
122 |
123 | 다음의 코드 예제에서는 이 컨셉을 보여줍니다:
124 |
125 | ```text
126 | public class DataAccess : IDataAccess
127 | {
128 | // 생성자는 의존성 주입에 의하여 HttpClient의 인스턴스를 받게 됩니다.
129 | // HttpClient는 Blazor가 기본으로 제공하는 서비스입니다.
130 | public DataAccess(HttpClient client)
131 | {
132 | ...
133 | }
134 | ...
135 | }
136 | ```
137 |
138 | 생성자 주입을 사용하려면 다음의 조건을 만족해야 합니다:
139 |
140 | * 의존성 주입에 의하여 매개 변수를 제공할 수 있는 생성자가 한 개만 있어야 합니다. 단, 기본값이 지정된 매개 변수들은 의존성 주입에 의하여 처리되지 않더라도 사용할 수 있습니다.
141 | * 반드시 _public_ 으로 선언된 생성자여야 합니다.
142 | * 조건에 만족하는 생성자가 하나만 있어야 합니다. 조건을 만족하는 생성자가 여러 개여서 모호한 상황이 되면, 의존성 주입 처리 도중 예외를 발생시키게 됩니다.
143 |
144 | ### 추가 리소스
145 |
146 | * [ASP.NET Core에서의 의존성 주입](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection)
147 |
148 |
--------------------------------------------------------------------------------
/faq.md:
--------------------------------------------------------------------------------
1 | # 자주 묻는 질문들
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | ## Blazor란 무엇인가요?
6 |
7 | Blazor는 단일 페이지 웹 앱 \(SPA\) 프레임워크로 브라우저 안에서 웹 어셈블리로 실행되며, .NET으로 만들어졌습니다.
8 |
9 | ## .NET을 처음 들어보는데, .NET은 무엇인가요?
10 |
11 | [.NET](https://www.microsoft.com/net) 은 무료로 제공되며, 크로스 플랫폼이면서, 서로 다른 수많은 종류의 앱 \(데스크탑, 모바일, 게임, 웹\)을 만들기 위한 오픈 소스 개발자 플랫폼입니다. .NET에는 관리되는 런타임, 표준화된 [라이브러리](https://docs.microsoft.com/dotnet/api)가 포함되어있으며, 그리고 여러 모던 프로그래밍 언어들: [C\#](https://docs.microsoft.com/dotnet/csharp/), [F\#](https://docs.microsoft.com/dotnet/fsharp/), 그리고 [VB](https://docs.microsoft.com/dotnet/visual-basic/)를 지원합니다. [10분 안에 .NET 시작하기](https://www.microsoft.com/net/learn/get-started/windows) 가이드를 참고하여 .NET을 배울 수 있습니다.
12 |
13 | ## .NET을 웹 개발을 위하여 왜 사용해야 합니까?
14 |
15 | 브라우저 안에서 .NET을 사용하면 웹 개발을 보다 쉽고 생산적으로 만들기 위한 많은 장점을 누릴 수 있습니다:
16 |
17 | * **안정성과 일관성**: .NET은 표준 API, 도구, 그리고 빌드 인프라를 모든 .NET 플랫폼에 걸쳐 안정적이고, 풍부한 기능을 제공하면서도, 사용하기 쉽게 제공합니다.
18 | * **혁신적인 모던 언어**: .NET의 여러 언어들 중 [C\#](https://docs.microsoft.com/dotnet/csharp/) 과 [F\#](https://docs.microsoft.com/dotnet/fsharp/)은 여러 새롭고 혁신적인 언어 기능들을 통하여 프로그래밍을 더 재미있고 더 향상시킬 수 있게 도와줍니다.
19 | * **업계를 선도하는 도구**: [Visual Studio](https://www.visualstudio.com/) 제품군은 최고의 .NET 개발 환경을 Windows, Linux, 그리고 macOS에서 제공합니다.
20 | * **빠른 속도와 확장성**: .NET은 성능, 안정성, 그리고 보안을 서버에서 제공하기 위한 긴 경험을 가지고 있습니다. .NET을 풀 스택 솔루션으로서 사용하면 여러분의 앱을 더 손쉽게 확장할 수 있습니다.
21 |
22 | ## .NET을 웹 브라우저에서 어떻게 실행할 수 있는건가요?
23 |
24 | .NET을 브라우저에서 실행할 수 있는 것은 새로운 웹 표준 기술인 [웹 어셈블리](http://webassembly.org/)에 의하여 가능해 졌습니다. 웸 어셈블리는 "웹으로의 컴파일에 적합한 이식 가능한 크기 및 빠른 로딩 시간을 보장하는 형식"입니다. 웹 어셈블리로 컴파일된 코드는 어떤 브라우저에서든 네이티브와 같은 속도로 실행할 수 있습니다. .NET 바이너리를 웹 브라우저에서 실행하기 위해서는, 웹 어셈블리로 컴파일된 .NET 런타임 \(구체적으로는 [Mono](http://www.mono-project.com/news/2017/08/09/hello-webassembly/)\)을 사용해야 합니다.
25 |
26 | ## Blazor는 내가 만든 .NET 기반의 앱을 통째로 웹 어셈블리로 컴파일합니까?
27 |
28 | 아니오, 하나의 Blazor 앱은 보통의 컴파일된 .NET 어셈블리로 웹 어셈블리 기반의 .NET 런타임을 사용하여 웹 브라우저에 의하여 다운로드되고 실행됩니다. .NET 런타임 그 자체만이 웹 어셈블리로서 컴파일됩니다. 나중에는 앱의 전체 코드를 [정적 \(AoT\) 컴파일](http://www.mono-project.com/news/2018/01/16/mono-static-webassembly-compilation/) 기능을 사용하여 웹 어셈블리로 변환하는 것을 추가하게 될 수도 있습니다.
29 |
30 | ## .NET 런타임을 포함하는 것이라면, 앱의 전체 다운로드 크기가 매우 크지 않을까요?
31 |
32 | 반드시 그렇지는 않습니다. .NET 런타임은 모든 형태의 크기로 제공됩니다. 초기의 Blazor 프로토타입은 경량화된 .NET 런타임 \(어셈블리 실행, 가비지 컬렉션, 스레딩 기능을 제공하는\) 을 사용하여 60KB 내외의 웹 어셈블리로 컴파일되도록 만들어졌습니다. 이제 Blazor는 이전보다 훨씬 크기가 큰 Mono 위에서 실행됩니다. 하지만, 그러나 런타임 및 응용 프로그램 바이너리의 병합 및 트리밍을 비롯하여, 아직 전송될 파일들의 크기에 관해서는 최적화할 여지가 많이 남았습니다. 그 외에도, 캐싱과 CDN을 사용하는 전략도 생각하고 있습니다.
33 |
34 | ## Blazor에서는 앞으로 어떤 기능을 지원하게 됩니까?
35 |
36 | Blazor는 모던 SPA 프레임워크라면 기대할 수 있는 다음의 기능들을 지원할 것입니다:
37 |
38 | * 조합 가능한 UI를 만들기 위한 컴포넌트 모델
39 | * 라우팅
40 | * 레이아웃
41 | * 폼과 유효성 검사
42 | * 의존성 주입
43 | * JavaScript 연동
44 | * 개발 중에 동적 새로 고침 지원
45 | * 서버 측 렌더링
46 | * 브라우저와 IDE에서 모두 사용 가능한 완전한 .NET 디버깅 지원
47 | * 개선된 IntelliSense 지원과 도구
48 | * asm.js를 통한 오래된 \(웹 어셈블리를 지원하지 않는\) 브라우저에서의 실행 지원
49 | * 게시 및 앱 크기 최적화
50 |
51 | ## 서버가 .NET을 사용하지 않아도 Blazor 앱을 실행할 수 있습니까?
52 |
53 | 예. Blazor 앱은 정적 파일들로 배포되기 때문에 서버가 .NET을 지원하는지의 여부는 아무런 상관이 없습니다.
54 |
55 | ## Blazor를 서버의 ASP.NET Core와 함께 사용할 수 있습니까?
56 |
57 | 예! Blazor는 부수적으로 [ASP.NET Core](https://docs.microsoft.com/aspnet/core)와의 연동을 통하여 자연스럽고 일관성있는 풀 스택 웹 개발 솔루션을 제공합니다.
58 |
59 | ## Blazor는 기존 JavaScript 프레임워크를 .NET으로 포팅한 버전입니까?
60 |
61 | Blazor는 기존의 모던 SPA 앱 프레임워크인 React, Angular, 그리고 Vue에서 영감을 얻어 만든 _새로운 프레임워크_ 입니다.
62 |
63 | ## Blazor를 어떻게 테스트해볼 수 있나요?
64 |
65 | 첫 Blazor 웹 앱을 만들기 위해서는 [Blazor 시작하기](get-started.md) 문서를 참고하세요.
66 |
67 | ## 왜 Blazor는 "실험용" 프로젝트인가요?
68 |
69 | Blazor는 실험적 프로젝트입니다. 왜냐하면 쓰임새와 유용성에 대해서 풀어야 할 과제들이 많이 남았기 때문입니다. 이 실험용 프로젝트의 초기 목적은 다음과 같습니다.
70 |
71 | * Work through technical issues.
72 | * Gauge interest and to listen to feedback.
73 |
74 | Blazor의 미래에 대해서는 낙관적으로 보고 있습니다. 그러나 지금 Blazor는 완전한 제품이 아니며, 극 초기 단계의 프로토타입으로서만 고려되어야 합니다.
75 |
76 | ## Silverlight와 같은 일을 새로 시작하는건가요?
77 |
78 | 아니오, Blazor는 HTML과 CSS를 기반으로 하는 .NET 웹 프레임워크로 공개된 웹 표준을 사용하여 브라우저 안에서 실행됩니다. 플러그인은 전혀 필요하지 않으며, 모바일 장치와 오래된 브라우저에서도 실행됩니다.
79 |
80 | ## Blazor는 XAML을 사용합니까?
81 |
82 | 아니오, Blazor는 HTML, CSS, 그리고 다른 표준 웹 기술을 기반으로하는 웹 프레임워크입니다.
83 |
84 | ## 웹 어셈블리는 모든 브라우저에서 지원됩니까?
85 |
86 | 네, WebAssembly는 크로스 브라우저에서 실행되기 위해 필요한 합의를 달성했고, [모든 최신 웹 브라우저들이 실행을 지원합니다.](https://caniuse.com/#search=webassembly).
87 |
88 | ## Blazor는 모바일 브라우저에서도 작동합니까?
89 |
90 | 네, [최신 모바일 브라우저들도 WebAssembly를 지원합니다.](https://caniuse.com/#search=webassembly).
91 |
92 | ## WebAssebmly를 지원하지 않는 오래된 브라우저들의 경우는 어떻습니까? 예를 들어, Blazor는 IE에서도 동작합니까?
93 |
94 | WebAssembly를 지원하지 않는 오래된 브라우저들에 대해서, Blazor는 더 느리고 더 많은 용량을 다운로드해야 하는 대신, 꽤 정상적인 기능을 보장하는 asm.js 기반의 .NET 런타임을 사용하도록 대처합니다.
95 |
96 | ## .NET Standard 라이브러리를 Blazor에서 사용할 수 있습니까?
97 |
98 | 네, Blazor를 위하여 사용되는 .NET 런타임은 .NET Standard 2.0을 지원합니다. 단, 브라우저 안에서 지원되지 않는 API들은 _기능이 지원되지 않음을 알리는 예외_ 를 발생시킵니다.
99 |
100 | ## Blazor가 동작하려면 WebAssembly에 가비지 수집 및 다중 스레드와 같은 기능이 추가되어야 하지 않습니까?
101 |
102 | 아니오, WebAssembly의 현재 상태로도 충분합니다. .NET 런타임이 자체적으로 가비지 수집과 다중 스레드에 대한 것을 처리합니다.
103 |
104 | ## 기존 JavaScript 라이브러리를 Blazor와 함께 사용할 수 있습니까?
105 |
106 | 예, Blazor 앱은 JavaScript를 JavaScript 상호 연동 API를 통하여 호출할 수 있습니다.
107 |
108 | ## Blazor 앱에서 DOM에 접근할 수 있습니까?
109 |
110 | .NET 코드에서 JavaScript 연동을 통해 DOM에 접근할 수는 있습니다. 하지만, Blazor는 DOM에 직접 접근해야 할 필요성을 최소화하는 컴포넌트 기반 프레임워크입니다.
111 |
112 | ## 왜 .NET Core나 CoreRT 대신 Mono를 택했나요?
113 |
114 | [Mono](http://www.mono-project.com/)는 Microsoft가 후원하는 .NET Framework의 오픈 소스 구현체입니다. Mono는 [Xamarin](https://www.xamarin.com/) 이 네이티브 클라이언트 앱을 Android, iOS, 그리고 macOS를 만들기 위하여 사용하고 있습니다. 또한 Mono는 [Unity](https://unity3d.com/) 가 게임 개발을 위하여 사용하고 있습니다. Microsoft의 Xamarin 팀은 Mono에 WebAssembly를 추가하기 위한 [계획을 발표하였고,](http://www.mono-project.com/news/2017/08/09/hello-webassembly/) 꾸준히 진행하고 있습니다. \([Mono와 WebAssembly - 정적 컴파일에 관한 소식 1/16/2018](http://www.mono-project.com/news/2018/01/16/mono-static-webassembly-compilation/)\). Blazor는 WebAssembly에 대해 동작하는 클라이언트 측 웹 UI 프레임워크이기 때문에, Mono를 선택하는 것이 가장 적절합니다.
115 |
116 | 반면에, [.NET Core](https://www.microsoft.com/net/learn/get-started/windows)는 주로 서버 앱과 크로스 플랫폼 콘솔 앱에 사용되는 것에 초점이 맞추어져 있습니다. .NET Core는 Blazor 앱을 위한 ASP.NET Core 백엔드를 만들 수 있지만, 클라이언트 앱 그 자체를 만드는 것은 아닙니다. [CoreRT](https://github.com/dotnet/corert)는 AoT 컴파일에 최적화된 .NET Core 런타임이며, WebAssembly에 대한 지원 계획도 가지고는 있지만, 아직 개발이 진행 중이며 완성된 제품이 아닙니다.
117 |
118 | ## "Blazor" 라는 이름은 어디에서 온 것입니까?
119 |
120 | Blazor는 [Razor](https://docs.microsoft.com/aspnet/core/mvc/views/razor?view=aspnetcore-2.1)라는 HTML과 C\#을 위한 마크업 언어를 매우 많이 사용합니다. **즉, Browser + Razor = Blazor 입니다!** 발음할 때에도, 패션, 스타일, 그리고 프로그래밍 언어에 대한 탁월한 감각을 지닌 힙스터들이 즐겨 입는 멋진 재킷의 이름과도 비슷합니다.
121 |
122 |
--------------------------------------------------------------------------------
/get-started.md:
--------------------------------------------------------------------------------
1 | # Blazor 시작하기
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | ## 설치하기
6 |
7 | 다음을 설치하세요:
8 |
9 | 1. [.NET Core 2.1 SDK](https://go.microsoft.com/fwlink/?linkid=873092) \(2.1.402 이상\).
10 | 2. [Visual Studio 2017](https://go.microsoft.com/fwlink/?linkid=873093) \(15.8 이상\)을 _ASP.NET과 웹 개발 워크로드_를 선택하여 함께 설치하세요.
11 | 3. 최신 버전의 [Blazor 언어 서비스 확장팩](https://go.microsoft.com/fwlink/?linkid=870389)을 Visual Studio 마켓플레이스를 통해 설치하세요.
12 | 4. 명령줄 도구에서 다음과 같이 Blazor 템플릿을 설치합니다:
13 |
14 | ```text
15 | dotnet new -i Microsoft.AspNetCore.Blazor.Templates
16 | ```
17 |
18 | Visual Studio에서 첫 프로젝트를 만들려면:
19 |
20 | 1. **파일** > **새 프로젝트** > **웹** > **ASP.NET Core 웹 애플리케이션**을 선택하세요.
21 | 2. 반드시 **.NET Core**와 **ASP.NET Core 2.1**을 창 위에서 선택하세요.
22 | 3. Blazor 템플릿을 선택하고 **확인**을 누르세요.
23 |
24 | 
25 |
26 | 4. 키보드에서 **Ctrl키와 F5키**를 눌러 _디버거 없이 앱을 실행_합니다. 디버거를 연결하여 실행하는 기능 \(**F5**\)은 아직 지원되지 않습니다.
27 |
28 | 명령줄에서 새 Blazor 앱을 만들려면:
29 |
30 | ```text
31 | dotnet new blazor -o BlazorApp1
32 | cd BlazorApp1
33 | dotnet run
34 | ```
35 |
36 | 축하합니다! 여러분은 이제 첫 Blazor 앱을 실행하셨습니다!
37 |
38 | 
39 |
40 | ## 도움말과 피드백
41 |
42 | 여러분의 피드백은 Blazor의 실험용 버전을 개발하는 데에 매우 요긴하게 사용됩니다. 만약 Blazor를 실행하면서 문제가 발생하거나 질문이 있다면, 꼭 알려주세요!
43 |
44 | * 어떤 종류이든 관계없이 문제가 발생하였거나, 혹은 제안과 개선 사항이 있다면 [GitHub에 이슈를 ](https://github.com/aspnet/blazor/issues)해주세요.
45 | * 만약 문제가 발생하거나 Blazor를 여러분이 원하는대로 동작하도록 수정한 경험이 있다면 Blazor 개발자들과 [Gitter](https://gitter.im/aspnet/blazor) 커뮤니티에서 대화하여 공유해주세요.
46 |
47 | Blazor를 테스트해본 다음에는, 제품과 함께 제공되는 설문 조사에 응답하셔서 여러분의 의견을 알려주세요. 기본 제공되는 Blazor 프로젝트 템플릿을 아무거나 하나 선택하여 앱을 실행하고, 아래 화면과 같이 앱 홈페이지에 있는 설문 조사 링크를 클릭하면 됩니다.
48 |
49 | 
50 |
51 | ## 다음 단계
52 |
53 | [첫 Blazor 앱 만들기](tutorials/build-your-first-blazor-app.md)
54 |
55 |
--------------------------------------------------------------------------------
/host-and-deploy/README.md:
--------------------------------------------------------------------------------
1 | # 호스팅 및 배포
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | ### Publish the app
6 |
7 | Blazor apps are published for deployment in Release configuration with the [dotnet publish](https://docs.microsoft.com/dotnet/core/tools/dotnet-publish)command. An IDE may handle executing the `dotnet publish` command automatically using its built-in publishing features, so it might not be necessary to manually execute the command from a command prompt depending on the development tools in use.
8 |
9 | ```text
10 | dotnet publish -c Release
11 | ```
12 |
13 | `dotnet publish` triggers a [restore](https://docs.microsoft.com/dotnet/core/tools/dotnet-restore) of the project's dependencies and [builds](https://docs.microsoft.com/dotnet/core/tools/dotnet-build) the project before creating the assets for deployment. As part of the build process, unused methods and assemblies are removed to reduce app download size and load times. The deployment is created in the _/bin/Release/<target-framework>/publish_ folder.
14 |
15 | The assets in the _publish_ folder are deployed to the web server. Deployment might be a manual or automated process depending on the development tools in use.
16 |
17 | ### Configure the Linker
18 |
19 | Blazor performs Intermediate Language \(IL\) linking on each build to remove unnecessary IL from the output assemblies. You can control assembly linking on build. For more information, see [Configure the Linker](https://blazor.net/docs/host-and-deploy/configure-linker.html).
20 |
21 | ### Rewrite URLs for correct routing
22 |
23 | Routing requests for page components in a client-side app isn't as simple as routing requests to a server-side, hosted app. Consider a client-side app with two pages:
24 |
25 | * _**Main.cshtml**_ – Loads at the root of the app and contains a link to the About page \(`href="About"`\).
26 | * _**About.cshtml**_ – About page.
27 |
28 | When the app's default document is requested using the browser's address bar \(for example, `https://www.contoso.com/`\):
29 |
30 | 1. The browser makes a request.
31 | 2. The default page is returned, which is usually _index.html_.
32 | 3. _index.html_ bootstraps the app.
33 | 4. Blazor's router loads and the Razor Main page \(_Main.cshtml_\) is displayed.
34 |
35 | On the Main page, selecting the link to the About page loads the About page. Selecting the link to the About page works on the client because the Blazor router stops the browser from making a request on the Internet to `www.contoso.com` for `About` and serves the About page itself. All of the requests for internal pages _within the client-side app_ work the same way: Requests don't trigger browser-based requests to server-hosted resources on the Internet. The router handles the requests internally.
36 |
37 | If a request is made using the browser's address bar for `www.contoso.com/About`, the request fails. No such resource exists on the app's Internet host, so a _404 Not found_ response is returned.
38 |
39 | Because browsers make requests to Internet-based hosts for client-side pages, web servers and hosting services must rewrite all requests for resources not physically on the server to the _index.html_ page. When _index.html_ is returned, the app's client-side router takes over and responds with the correct resource.
40 |
41 | ### App base path
42 |
43 | The app base path is the virtual app root path on the server. For example, an app that resides on the Contoso server in a virtual folder at `/CoolBlazorApp/` is reached at `https://www.contoso.com/CoolBlazorApp` and has a virtual base path of `/CoolBlazorApp/`. By setting the app base path to `CoolBlazorApp/`, the app is made aware of where it virtually resides on the server. The app can use the app base path to construct URLs relative to the app root from a component that isn't in the root directory. This allows components that exist at different levels of the directory structure to build links to other resources at locations throughout the app. The app base path is also used to intercept hyperlink clicks where the `href` target of the link is within the app base path URI space—the Blazor router handles the internal navigation.
44 |
45 | In many hosting scenarios, the server's virtual path to the app is the root of the app. In these cases, the app base path is a forward slash \(``\), which is the default configuration for a Blazor app. In other hosting scenarios, such as GitHub Pages and IIS virtual directories, the app base path must be set to the server's virtual path to the app. To set the Blazor app's base path, add or update the `` tag in _index.html_ found within the `` tag elements. Set the `href`attribute value to `/` \(the trailing slash is required\), where `/` is the full virtual app root path on the server for the app. In the preceding example, the virutal path is set to `CoolBlazorApp/`: ``.
46 |
47 | For an app with a non-root virtual path configured \(for example, ``\), the app fails to find its resources _when run locally_. To overcome this problem during local development and testing, you can supply a _path base_ argument that matches the `href` value of the `` tag at runtime.
48 |
49 | To pass the path base argument with the root path \(`/`\) when running the app locally, execute the following command from the Blazor app's directory:
50 |
51 | ```text
52 | dotnet run --pathbase=/CoolBlazorApp
53 | ```
54 |
55 | The app responds locally at `http://localhost:port/CoolBlazorApp`.
56 |
57 | For more information, see the [path base host configuration value](https://blazor.net/docs/host-and-deploy/index.html#path-base) section.
58 |
59 | **IMPORTANT**
60 |
61 | If a Blazor app uses the [client-side hosting model](https://blazor.net/docs/host-and-deploy/hosting-models.html#client-side-hosting-model) \(based on the **Blazor** project template\) and is hosted as an IIS sub-application in an ASP.NET Core app, it's important to disable the inherited ASP.NET Core Module handler. Remove the handler in the Blazor app's published _web.config_ file by adding a `` section to the file:
62 |
63 | ```text
64 |
65 |
66 |
67 | ```
68 |
69 | Removing the handler is performed in addition to configuring the app's base path as described in this section. Set the app base path in the Blazor app's _index.html_ file to the IIS alias used when configuring the sub-app in IIS.
70 |
71 | ### Host configuration values
72 |
73 | Blazor apps that use the [server-side hosting model](https://blazor.net/docs/host-and-deploy/hosting-models.html#server-side-hosting-model) can accept [Web Host configuration values](https://docs.microsoft.com/aspnet/core/fundamentals/host/web-host#host-configuration-values).
74 |
75 | Blazor apps that use the [client-side hosting model](https://blazor.net/docs/host-and-deploy/hosting-models.html#client-side-hosting-model) can accept the following host configuration values as command-line arguments at runtime in the development environment.
76 |
77 | #### Content Root
78 |
79 | The `--contentroot` argument sets the absolute path to the directory that contains the app's content files.
80 |
81 | * Pass the argument when running the app locally at a command prompt. From the app's directory, execute:
82 |
83 | ```text
84 | dotnet run --contentroot=/
85 | ```
86 |
87 | * Add an entry to the app's _launchSettings.json_ file in the **IIS Express** profile. This setting is picked up when running the app with the Visual Studio Debugger and when running the app from a command prompt with `dotnet run`.
88 |
89 | ```text
90 | "commandLineArgs": "--contentroot=/"
91 | ```
92 |
93 | * In Visual Studio, specify the argument in **Properties** > **Debug** > **Application arguments**. Setting the argument in the Visual Studio property page adds the argument to the _launchSettings.json_ file.
94 |
95 | ```text
96 | --contentroot=/
97 | ```
98 |
99 | #### Path base
100 |
101 | The `--pathbase` argument sets the app base path for an app run locally with a non-root virtual path \(the `` tag `href` is set to a path other than `/` for staging and production\). For more information, see the [App base path](https://blazor.net/docs/host-and-deploy/index.html#app-base-path) section.
102 |
103 | **IMPORTANT**
104 |
105 | Unlike the path provided to `href` of the `` tag, don't include a trailing slash \(`/`\) when passing the `--pathbase` argument value. If the app base path is provided in the `` tag as `` \(includes a trailing slash\), pass the command-line argument value as `--pathbase=/CoolBlazorApp` \(no trailing slash\).
106 |
107 | * Pass the argument when running the app locally at a command prompt. From the app's directory, execute:
108 |
109 | ```text
110 | dotnet run --pathbase=/
111 | ```
112 |
113 | * Add an entry to the app's _launchSettings.json_ file in the **IIS Express** profile. This setting is picked up when running the app with the Visual Studio Debugger and when running the app from a command prompt with `dotnet run`.
114 |
115 | ```text
116 | "commandLineArgs": "--pathbase=/"
117 | ```
118 |
119 | * In Visual Studio, specify the argument in **Properties** > **Debug** > **Application arguments**. Setting the argument in the Visual Studio property page adds the argument to the _launchSettings.json_ file.
120 |
121 | ```text
122 | --pathbase=/
123 | ```
124 |
125 | #### URLs
126 |
127 | The `--urls` argument indicates the IP addresses or host addresses with ports and protocols to listen on for requests.
128 |
129 | * Pass the argument when running the app locally at a command prompt. From the app's directory, execute:
130 |
131 | ```text
132 | dotnet run --urls=http://127.0.0.1:0
133 | ```
134 |
135 | * Add an entry to the app's _launchSettings.json_ file in the **IIS Express** profile. This setting is picked up when running the app with the Visual Studio Debugger and when running the app from a command prompt with `dotnet run`.
136 |
137 | ```text
138 | "commandLineArgs": "--urls=http://127.0.0.1:0"
139 | ```
140 |
141 | * In Visual Studio, specify the argument in **Properties** > **Debug** > **Application arguments**. Setting the argument in the Visual Studio property page adds the argument to the _launchSettings.json_ file.
142 |
143 | ```text
144 | --urls=http://127.0.0.1:0
145 | ```
146 |
147 | ### Deployment models
148 |
149 | There are two deployment models for Blazor apps:
150 |
151 | * [Hosted deployment with ASP.NET Core](https://blazor.net/docs/host-and-deploy/index.html#hosted-deployment-with-aspnet-core) – Hosted deployment uses an ASP.NET Core app on the server to host the Blazor app.
152 | * [Standalone deployment](https://blazor.net/docs/host-and-deploy/index.html#standalone-deployment) – Standalone deployment places the Blazor app on a static hosting web server or service, where .NET isn't used to serve the Blazor app.
153 |
154 | #### Hosted deployment with ASP.NET Core
155 |
156 | In a hosted deployment, an ASP.NET Core app handles single-page application routing and Blazor app hosting. The published ASP.NET Core app, along with one or more Blazor apps that it hosts, is deployed to the web server or hosting service.
157 |
158 | To host a Blazor app, the ASP.NET Core app must:
159 |
160 | * Reference the Blazor app project.
161 | * Reference the [Microsoft.AspNetCore.Blazor.Server](https://www.nuget.org/packages/Microsoft.AspNetCore.Blazor.Server/) package in its project file.
162 | * Configure Blazor app hosting with the `UseBlazor` extension method on [IApplicationBuilder](https://docs.microsoft.com/dotnet/api/microsoft.aspnetcore.builder.iapplicationbuilder)in `Startup.Configure`.
163 |
164 | ```text
165 | public void Configure(IApplicationBuilder app, IHostingEnvironment env)
166 | {
167 | if (env.IsDevelopment())
168 | {
169 | app.UseDeveloperExceptionPage();
170 | }
171 |
172 | app.UseBlazor();
173 | }
174 | ```
175 |
176 | The `UseBlazor` extension method performs the following tasks:
177 |
178 | * Configure [Static File Middleware](https://docs.microsoft.com/aspnet/core/fundamentals/static-files) to serve Blazor's static assets from the _dist_ folder. In the Development environment, the files in _wwwroot_ folder are served.
179 | * Configure single-page application routing for resource requests that aren't for actual files that exist on disk. The app serves the default document \(_wwwroot/index.html_\) for any request that hasn't been served by a prior Static File Middleware instance. For example, a request to receive a page from the app that should be handled by the Blazor router on the client is rewritten into a request for the _wwwroot/index.html_ page.
180 |
181 | When the ASP.NET Core app is published, the Blazor app is included in the published output so that the ASP.NET Core app and the Blazor app can be deployed together. For more information on ASP.NET Core app hosting and deployment, see [Host and deploy ASP.NET Core](https://docs.microsoft.com/aspnet/core/host-and-deploy).
182 |
183 | For information on deploying to Azure App Service, see the following topics:
184 |
185 | [Publish to Azure with Visual Studio](https://docs.microsoft.com/aspnet/core/tutorials/publish-to-azure-webapp-using-vs)
186 | Learn how to publish an ASP.NET Core-hosted Blazor app to Azure App Service using Visual Studio.
187 |
188 | [Publish to Azure with CLI tools](https://docs.microsoft.com/aspnet/core/tutorials/publish-to-azure-webapp-using-cli)
189 | Learn how to publish an ASP.NET Core app to Azure App Service using the Git command-line client.
190 |
191 | #### Standalone deployment
192 |
193 | In a standalone deployment, only the Blazor client-side app is deployed to the server or hosting service. An ASP.NET Core server-side app isn't used to host the Blazor app. The Blazor app's static files are requested by the browser directly from the static file web server or service.
194 |
195 | When deploying a standalone Blazor app from the published _dist_ folder, any web server or hosting service that serves static files can host a Blazor app.
196 |
197 | **IIS**
198 |
199 | IIS is a capable static file server for Blazor apps. To configure IIS to host Blazor, see [Build a Static Website on IIS](https://docs.microsoft.com/iis/manage/creating-websites/scenario-build-a-static-website-on-iis).
200 |
201 | Published assets are created in the _\bin\Release\<target-framework>\publish_ folder. Host the contents of the _publish_ folder on the web server or hosting service.
202 |
203 | **web.config**
204 |
205 | When a Blazor project is published, a _web.config_ file is created with the following IIS configuration:
206 |
207 | * MIME types are set for the following file extensions:
208 | * _\*.dll_: `application/octet-stream`
209 | * _\*.json_: `application/json`
210 | * _\*.wasm_: `application/wasm`
211 | * _\*.woff_: `application/font-woff`
212 | * _\*.woff2_: `application/font-woff`
213 | * HTTP compression is enabled for the following MIME types:
214 | * `application/octet-stream`
215 | * `application/wasm`
216 | * URL Rewrite Module rules are established:
217 | * Serve the sub-directory where the app's static assets reside \(_<assembly\_name>\dist\<path\_requested>_\).
218 | * Create SPA fallback routing so that requests for non-file assets are redirected to the app's default document in its static assets folder \(_<assembly\_name>\dist\index.html_\).
219 |
220 | **Install the URL Rewrite Module**
221 |
222 | The [URL Rewrite Module](https://www.iis.net/downloads/microsoft/url-rewrite) is required to rewrite URLs. The module isn't installed by default, and it isn't available for install as an Web Server \(IIS\) role service feature. The module must be downloaded from the IIS website. Use the Web Platform Installer to install the module:
223 |
224 | 1. Locally, navigate to the [URL Rewrite Module downloads page](https://www.iis.net/downloads/microsoft/url-rewrite#additionalDownloads). For the English version, select **WebPI** to download the WebPI installer. For other languages, select the appropriate architecture for the server \(x86/x64\) to download the installer.
225 | 2. Copy the installer to the server. Run the installer. Select the **Install** button and accept the license terms. A server restart isn't required after the install completes.
226 |
227 | **Configure the website**
228 |
229 | Set the website's **Physical path** to the Blazor app's folder. The folder contains:
230 |
231 | * The _web.config_ file that IIS uses to configure the website, including the required redirect rules and file content types.
232 | * The app's static asset folder.
233 |
234 | **Troubleshooting**
235 |
236 | If a _500 Internal Server Error_ is received and IIS Manager throws errors when attempting to access the website's configuration, confirm that the URL Rewrite Module is installed. When the module isn't installed, the _web.config_ file can't be parsed by IIS. This prevents the IIS Manager from loading the website's configuration and the website from serving Blazor's static files.
237 |
238 | For more information on troubleshooting deployments to IIS, see [Troubleshoot ASP.NET Core on IIS](https://docs.microsoft.com/aspnet/core/host-and-deploy/iis/troubleshoot).
239 |
240 | **Nginx**
241 |
242 | The following _nginx.conf_ file is simplified to show how to configure Nginx to send the _Index.html_file whenever it can't find a corresponding file on disk.
243 |
244 | ```text
245 | events { }
246 | http {
247 | server {
248 | listen 80;
249 |
250 | location / {
251 | root /usr/share/nginx/html;
252 | try_files $uri $uri/ /Index.html =404;
253 | }
254 | }
255 | }
256 | ```
257 |
258 | For more information on production Nginx web server configuration, see [Creating NGINX Plus and NGINX Configuration Files](https://docs.nginx.com/nginx/admin-guide/basic-functionality/managing-configuration-files/).
259 |
260 | **Nginx in Docker**
261 |
262 | To host Blazor in Docker using Nginx, setup the Dockerfile to use the Alpine-based Nginx image. Update the Dockerfile to copy the _nginx.config_ file into the container.
263 |
264 | Add one line to the Dockerfile, as shown in the following example:
265 |
266 | ```text
267 | FROM nginx:alpine
268 | COPY ./bin/Release/netstandard2.0/publish /usr/share/nginx/html/
269 | COPY nginx.conf /etc/nginx/nginx.conf
270 | ```
271 |
272 | **GitHub Pages**
273 |
274 | To handle URL rewrites, add a _404.html_ file with a script that handles redirecting the request to the _index.html_ page. For an example implementation provided by the community, see [Single Page Apps for GitHub Pages](http://spa-github-pages.rafrex.com/) \([rafrex/spa-github-pages on GitHub](https://github.com/rafrex/spa-github-pages#readme)\). An example using the community approach can be seen at [blazor-demo/blazor-demo.github.io on GitHub](https://github.com/blazor-demo/blazor-demo.github.io) \([live site](https://blazor-demo.github.io/)\).
275 |
276 | When using a project site instead of an organization site, add or update the `` tag in _index.html_. Set the `href` attribute value to `/`, where `/`is the GitHub repository name.
277 |
278 |
--------------------------------------------------------------------------------
/host-and-deploy/configure-linker.md:
--------------------------------------------------------------------------------
1 | # 링커 설정하기
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | Blazor performs [Intermediate Language \(IL\)](https://docs.microsoft.com/dotnet/standard/managed-code#intermediate-language--execution) linking during each Release mode build to remove unnecessary IL from the output assemblies.
6 |
7 | You can control assembly linking with either of the following approaches:
8 |
9 | * Disable linking globally with an MSBuild property.
10 | * Control linking on a per-assembly basis with a configuration file.
11 |
12 | ### Disable linking with an MSBuild property
13 |
14 | Linking is enabled by default in Release mode when an app is built, which includes publishing. To disable linking for all assemblies, set the `` MSBuild property to `false` in the project file:
15 |
16 | ```text
17 |
18 | false
19 |
20 | ```
21 |
22 | ### Control linking with a configuration file
23 |
24 | Linking can be controlled on a per-assembly basis by providing an XML configuration file and specifying the file as an MSBuild item in the project file.
25 |
26 | The following is an example configuration file \(_Linker.xml_\):
27 |
28 | ```text
29 |
30 |
34 |
35 |
36 |
41 |
42 |
43 |
44 |
48 |
49 |
50 |
54 |
55 |
56 | ```
57 |
58 | To learn more about the file format for the configuration file, see [IL Linker: Syntax of xml descriptor](https://github.com/mono/linker/blob/master/linker/README.md#syntax-of-xml-descriptor).
59 |
60 | Specify the configuration file in the project file with the `BlazorLinkerDescriptor` item:
61 |
62 | ```text
63 |
64 |
65 |
66 | ```
67 |
68 |
--------------------------------------------------------------------------------
/host-and-deploy/hosting-models.md:
--------------------------------------------------------------------------------
1 | # 호스팅 모델
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 |
6 |
7 | Blazor is a client-side web framework designed primarily to run in the browser on a WebAssembly-based .NET runtime. Blazor supports multiple hosting models, including out-of-process hosting models, where the Blazor component logic runs separately from the UI thread. Regardless of the hosting model, the Blazor app and component models remain _the same_. This article discusses the available hosting models for Blazor.
8 |
9 | ### Client-side hosting model
10 |
11 | The principal hosting model for Blazor is running client-side in the browser. In this model, the Blazor app, its dependencies, and the .NET runtime are downloaded to the browser, and the app is executed directly on the browser UI thread. All UI updates and event handling happens within the same process. The app assets can be deployed as static files using whatever web server is preferred \(see [Host and deploy](https://blazor.net/docs/host-and-deploy/index.html)\).
12 |
13 | 
14 |
15 | To create a Blazor app using the client-side hosting model, use the **Blazor** or **Blazor \(ASP.NET Core Hosted\)** project templates \(`blazor` or `blazorhosted` template when using [dotnet new](https://blazor.net/dotnet/core/tools/dotnet-new) at a command prompt\). The included _blazor.webassembly.js_ script handles:
16 |
17 | * Downloading the .NET runtime, the app, and its dependencies.
18 | * Initialization of the runtime to run the app.
19 |
20 | The benefits of the client-side hosting model are:
21 |
22 | * No .NET server-side dependency
23 | * Rich interactive UI
24 | * Fully leverage the client resources and capabilities
25 | * Offload work from the server to the client
26 | * Support offline scenarios
27 |
28 | The downsides to the client-side hosting model are:
29 |
30 | * Restricted to the capabilities of the browser
31 | * Requires more capable client hardware and software \(for example, WebAssembly support\)
32 | * Larger download size and app load time
33 | * Less mature .NET runtime and tooling support \(for example, limitations in .NET Standard support and debugging\)
34 |
35 | **NOTE**
36 |
37 | Visual Studio includes the **Blazor \(ASP.NET Core hosted\)** project template for creating a Blazor app that runs on WebAssembly and is hosted on an ASP.NET Core server. The ASP.NET Core app serves the Blazor app to clients but is otherwise a separate process. The client-side Blazor app can interact with the server over the network using Web API calls or SignalR connections.
38 |
39 | **IMPORTANT**
40 |
41 | If a client-side Blazor app is served by an ASP.NET Core app hosted as an IIS sub-app, it's important to disable the inherited ASP.NET Core Module handler. Remove the handler in the Blazor app's published _web.config_ file by adding a `` section to the file:
42 |
43 | ```text
44 |
45 |
46 |
47 | ```
48 |
49 | Set the app base path in the Blazor app's _index.html_ file to the IIS alias used when configuring the sub-app in IIS. For more information, see [App base path](https://blazor.net/docs/host-and-deploy/index.html#app-base-path).
50 |
51 | ### Server-side hosting model
52 |
53 | In the server-side hosting model, Blazor is executed on the server from within an ASP.NET Core app. UI updates, event handling, and JavaScript calls are handled over a SignalR connection.
54 |
55 | 
56 |
57 | To create a Blazor app using the server-side hosting model, use the **Blazor \(Server-side on ASP.NET Core\)** template \(`blazorserver` when using [dotnet new](https://blazor.net/dotnet/core/tools/dotnet-new) at a command prompt\). An ASP.NET Core app hosts the Blazor server-side app and sets up the SignalR endpoint where clients connect. The ASP.NET Core app references the Blazor `Startup` class to both add the server-side Blazor services and to add the Blazor app to the request handling pipeline:
58 |
59 | ```text
60 | public class Startup
61 | {
62 | public void ConfigureServices(IServiceCollection services)
63 | {
64 | ...
65 | services.AddServerSideBlazor();
66 | }
67 |
68 | public void Configure(IApplicationBuilder app, IHostingEnvironment env)
69 | {
70 | ...
71 | app.UseServerSideBlazor();
72 | }
73 | }
74 | ```
75 |
76 | The _blazor.server.js_ script establishes the client connection. It's the app's responsibility to persist and restore app state as needed \(for example, in the event of a lost network connection\).
77 |
78 | The benefits of the server-side hosting model are:
79 |
80 | * You can still write your entire app with .NET and C\# using the Blazor component model.
81 | * Your app still has a rich interactive feel and avoids unnecessary page refreshes.
82 | * Your app download size is significantly smaller, and the initial app load time is much faster.
83 | * Your Blazor component logic can take full advantage of server capabilities, including using any .NET Core compatible APIs.
84 | * Because you're running on .NET Core on the server, existing .NET tooling, such as debugging, works as expected.
85 | * Server-side hosting works with thin clients \(for example, browsers that don't support WebAssembly and resource constrained devices\).
86 |
87 | The downsides of the server-side hosting model are:
88 |
89 | * Latency: every user interaction now involves a network hop.
90 | * No offline support: if the client connection goes down, the app stops working.
91 | * Scalability: the server must manage multiple client connections and handle client state.
92 |
93 |
--------------------------------------------------------------------------------
/introduction.md:
--------------------------------------------------------------------------------
1 | # Blazor 소개
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | Blazor는 브라우저 안에서 WebAssembly로 실행되는 C\#/Razor와 HTML을 사용하는 실험용 .NET 웹 프레임워크입니다. Blazor는 클라이언트 측에서 .NET을 사용하여 얻을 수 있는 \(부수적으로 서버에서 사용하는 경우까지 포함하여\) 클라이언트 측 웹 UI 프레임워크의 모든 이점을 제공합니다.
6 |
7 | ## 왜 브라우저에서 .NET을 사용합니까?
8 |
9 | 지난 수년간 웹 개발 기술은 다양한 방식으로 개선되어왔지만, 여전히 모던 웹 앱을 만드는 것은 도전적인 면이 있습니다. .NET을 브라우저에서 사용하면 웹 개발을 더 쉽고 더 생산적으로 만드는데 도움을 주는 여러 장점들이 있습니다:
10 |
11 | * **안정성과 일관성**: .NET은 여러 플랫폼에 걸쳐서 안정적이고, 풍분한 기능을 제공하며, 사용하기 쉬운 표준화된 프로그래밍 프레임워크를 제공합니다.
12 | * **혁신적인 모던 프로그래밍 언어**: .NET의 언어들은 혁신적인 새로운 언어 기능과 함께 꾸준히 개선되어 왔습니다.
13 | * **업계 표준의 도구**: Visual Studio 제품군은 환상적인 .NET 개발 환경을 Windos, Linux, 그리고 macOS에 대해 제공합니다.
14 | * **속도와 확장성**: .NET은 앱 개발을 위한 성능, 안정성, 그리고 보안에 대한 강한 기반을 가지고 있습니다. .NET을 풀 스택 솔루션으로 사용하면 빠르고, 안정적이며, 안전한 앱을 만드는 것이 더 쉬워집니다.
15 | * **기존 스킬을 활용하는 풀 스택 개발**: C\#/Razor 개발자는 기존의 C\#/Razor 스킬을 이용하여 클라이언트 측 코드를 작성하고, 서버와 클라이언트 로직을 앱 간에 공유할 수 있습니다.
16 | * **폭 넓은 브라우저 지원**: Blazor는 별도의 플러그인이나 코드 변환없이 브라우저에서 공개 웹 표준을 사용하여 실행되는 환경 위의 .NET에서 실행됩니다. 모바일 브라우저를 포함한 모든 최신 웹 브라우저에서 동작합니다.
17 |
18 | ## Blazor가 브라우저 안에서 .NET을 실행하는 원리
19 |
20 | 웹 브라우저 안에서 .NET 코드를 실행하는 것은 비교적 최신 기술인 [WebAssembly](http://webassembly.org/) \(이하 _wasm_ 으로 표기합니다.\) 덕분에 가능했습니다. WebAssembly는 공개 웹 표준으로 플러그인 없이 브라우저 안에서 사용할 수 있습니다. WebAssembly는 빠른 다운로드와 실행 속도에 최적화된 최소한의 바이트코드 포맷입니다.
21 |
22 | WebAssembly 코드는 JavaScrpt 연동을 통하여 브라우저의 모든 기능에 접근할 수 있습니다. 동시에, WebAssembly 코드는 JavaScript가 실행되는 것과 동일한 안전한 샌드박스 안에서 실행되어, 클라이언트 장치에 위협을 줄 수 있는 동작이 차단됩니다.
23 |
24 | Blazor 앱을 만들고 브라우저 안에서 실행할 때에는:
25 |
26 | 1. C\# 코드 파일과 Razor 파일이 .NET 어셈블리로 컴파일됩니다.
27 | 2. 브라우저가 어셈블리와 .NET 런타임을 다운로드합니다.
28 | 3. Blazor는 JavaScript를 사용하여 .NET 런타임을 초기화하고, 필요한 어셈블리들을 불러들이도록 런타임을 구성합니다. 문서 개체 모델 \(DOM\) 을 조작하고 브라우저 API 호출을 JavaScript 상호 연동을 통하여 Blazor가 처리하게 됩니다.
29 |
30 | WebAssembly를 지원하지 않는 오래된 브라우저를 지원하기 위하여, Blazor는 [asm.js](https://wikipedia.org/wiki/Asm.js) 기반의 .NET 런타임을 대신 사용합니다.
31 |
32 | ## Blazor 컴포넌트
33 |
34 | Blazor 앱은 _컴포넌트_ 들로 구성됩니다. 하나의 컴포넌트는 페이지, 대화 상자, 또는 데이터 입력 양식과 같은 UI 조각입니다. 컴포넌트는 중첩되거나, 재사용되거나, 프로젝트 간에 공유될 수 있습니다.
35 |
36 | Blazor에서, 컴포넌트는 .NET 클래스입니다. 클래스는 C\# 클래스 \(_\*.cs_\) 로 직접 작성되거나, 혹은 더 많이 사용되는 형태로 Razor 마크업 페이지 \(_\*.cshtml_\)를 통하여 만들어 질 수 있습니다.
37 |
38 | [Razor](https://docs.microsoft.com/aspnet/core/mvc/views/razor) 는 C\# 코드와 HTML 마크업을 결합한 문법입니다. Razor는 개발자가 마크업와 C\#을 한 파일 안에서 [IntelliSense](https://docs.microsoft.com/visualstudio/ide/using-intellisense)를 사용하여 번갈아가며 사용할 수 있도록, 개발자의 생산성을 위하여 설계되었습니다. 다음은 _DialogComponent.cshtml_ Razor 파일 안에 정의한 기본적인 커스텀 대화 상자 마크업의 예시입니다:
39 |
40 | ```text
41 |
42 |
@Title
43 | @BodyContent
44 |
45 |
46 |
47 | @functions {
48 | public string Title { get; set; }
49 | public RenderFragment BodyContent { get; set; }
50 | public Action OnOK { get; set; }
51 | }
52 | ```
53 |
54 | 이 컴포넌트가 앱 안의 다른 위치에서 사용될 때, IntelliSense는 문법과 파라미터 자동 완성을 지원해줍니다.
55 |
56 | 컴포넌트는 다음과 같은 특징이 있습니다:
57 |
58 | * 중첩 가능합니다.
59 | * Razor \(_\*.cshtml_\) 또는 C\# \(_\*.cs_\) 코드로 만들 수 있습니다.
60 | * 클래스 라이브러리를 통하여 공유할 수 있습니다.
61 | * 브라우저 DOM 없이 단위 테스트를 만들 수 있습니다.
62 |
63 | ## 구조
64 |
65 | Blazor는 대부분의 앱이 필요로 하는 다음과 같은 내부 기능들을 제공합니다:
66 |
67 | * 레이아웃
68 | * 라우팅
69 | * 의존성 주입
70 |
71 | 이 기능들은 모두 부수적으로 사용할 수 있습니다. 앱에서 사용하지 않는 기능이 있으면, 앱이 나중에 [중간 언어 \(IL\) 링커](https://blazor.net/docs/host-and-deploy/configure-linker.html)를 통하여 내보내질 때 해당 기능의 구현이 제거된 채로 내보내집니다.
72 |
73 | ## 코드 공유와 .NET Standard
74 |
75 | Blazor 앱은 기존의 [.NET Standard](https://docs.microsoft.com/dotnet/standard/net-standard) 라이브러리를 참조하여 사용할 수 있습니다. .NET Standard는 여러 .NET 구현체들간의 공통된 일반화된 .NET API들의 사양입니다. Blazor는 .NET Standard 2.0 및 이후 버전을 지원합니다. 웹 브라우저 안에서 사용할 수 없는 API들 \(예를 들어, 파일 시스템에 접근하거나, 소켓을 열거나, 다중 스레드를 다루는 등\) 을 사용하려고 하면 [PlatformNotSupportedException](https://docs.microsoft.com/dotnet/api/system.platformnotsupportedexception) 예외가 발생합니다. .NET Standard 클래스 라이브러리들은 서버 코드와 브라우저 기반 앱 간에 공유할 수 있습니다.
76 |
77 | ## JavaScript 연동
78 |
79 | 서드파티 JavaScript 라이브러리와 브라우저 API가 필요한 앱을 위하여, WebAssembly는 JavaScript와 연동할 수 있도록 설계되어있습니다. Blazor는 모든 JavaScript 라이브러리와 API를 사용할 수 있습니다. C\# 코드는 JavaScript 코드를 호출할 수 있으며, JavaScript 코드는 C\# 코드를 호출할 수 있습니다. 더 자세한 정보는, [JavaScript 연동](javascript-interop.md) 문서를 참고하세요.
80 |
81 | ## 최적화
82 |
83 | 클라이언트 측 앱의 경우, 데이터 다운로드 크기는 매우 중요한 문제입니다. Blazor는 다운로드 크기를 최적화하여 다운로드 시간을 최소화합니다. 예를 들어, .NET 어셈블리에서 사용되지 않는 부분을 빌드 과정 중에 제거합니다. 그리고 HTTP 압축을 사용하거나, .NET 런타임과 어셈블리는 브라우저에서 캐시할 수 있습니다.
84 |
85 | ## 배포
86 |
87 | Blazor를 사용하여 완전히 독립된 클라이언트 측 앱을 만들거나, 서버와 클라이언트 앱을 모두 포함하는 풀 스택 ASP.NET Core 앱을 만들 수 있습니다.
88 |
89 | * **독립된 클라이언트 측 앱**을 만들면, Blazor 앱은 _dist_ 폴더 안에 정적 파일들로만 구성된 형태로 컴파일됩니다. 이 파일들은 Azure App Service, GitHub Pages, IIS \(정적 파일 제공 기능을 활성화해야 합니다.\), Node.js 서버, 그리고 수많은 서버와 서비스들 위에서 호스팅할 수 있습니다. 이 방식에서 서버에 .NET 런타임은 필요하지 않습니다.
90 | * **풀 스택 ASP.NET Core 앱**을 만들면, 코드를 서버와 클라이언트에서 공유할 수 있습니다. 만들어지는 ASP.NET Core 서버 앱은 Blazor의 클라이언트 측 UI과 서버 사이트 API 엔드포인트를 제공하며, ASP.NET Core를 지원하는 환경이라면 클라우드와 온 프레미스 환경 어디서나 실행 가능합니다.
91 |
92 |
--------------------------------------------------------------------------------
/javascript-interop.md:
--------------------------------------------------------------------------------
1 | # 자바스크립트 연동
2 |
3 | `노트: Blazor는 아직 기술 지원이 제공되지 않는 실험용 웹 프레임워크로, 실무 개발에 사용되어서는 안됩니다.`
4 |
5 | Blazor 앱에서는 .NET에서 자바스크립트 함수를 호출하고 자바스크립트 코드에서 .NET 메서드를 호출할 수 있습니다.
6 |
7 | ### .NET 메서드에서 자바스크립트 함수 호출
8 |
9 | Blazor .NET 코드에서 JavaScript 함수를 호출해야하는 경우가 있습니다. 예를 들어, 자바스크립트 호출(call)을 통해 브라우저 기능을 노출하거나 자바스크립트 라이브러리의 기능을 Blazor 앱으로 노출시킬 수 있습니다.
10 |
11 | .NET에서 자바스크립트를 호출하려면 `JSRuntime.Current`에서 액세스할 수 있는 `IJSRuntime` 추상화를 사용하십시오. `IJSRuntime`의 `InvokeAsync `메소드는 여러 개의 JSON 직렬화가능(serializable) 인수와 함께 호출하고자하는 자바스크립트 함수의 식별자 갖습니다. 함수 식별자는 전역 범위 \ (`window` \)에 따라 달라집니다. `window.someScope.someFunction`을 호출하려면 식별자는 someScope.someFunction이 됩니다. 함수가 호출되기 전에는 함수를 등록할 필요가 없습니다. 또한 반환 유형 'T'는 JSON을 직렬화 할 수 있어야합니다.
12 |
13 | 셈플 앱에서 다음 두 가지의 자바스크립트 함수를 클라이언트 측 앱에 사용하여 사용자의 입력을 받고 환영 인사말을 표시하기 위해 DOM과 상호작용도록 합니다.
14 |
15 | * `showPrompt` – 사용자의 입력\(사용자의 이름\)을 받기위한 프롬프트를 생성하고 호출자에게 해당 이름을 반환합니다.
16 | * `displayWelcome` – 호출자의 환영 인사말을 `id`가 `welcome`인 DOM 객체에 할당합니다.
17 |
18 | _wwwroot/exampleJsInterop.js_ 는 다음과 같습니다.
19 |
20 | ```text
21 | window.exampleJsFunctions = {
22 | showPrompt: function (text) {
23 | return prompt(text, 'Type your name here');
24 | },
25 | displayWelcome: function (welcomeMessage) {
26 | document.getElementById('welcome').innerText = welcomeMessage;
27 | },
28 | returnArrayAsyncJs: function () {
29 | DotNet.invokeMethodAsync('BlazorSample', 'ReturnArrayAsync')
30 | .then(data => {
31 | data.push(4);
32 | console.log(data);
33 | })
34 | },
35 | sayHello: function (dotnetHelper) {
36 | return dotnetHelper.invokeMethodAsync('SayHello')
37 | .then(r => console.log(r));
38 | }
39 | };
40 | ```
41 |
42 | 다음과 같이 자바스크립트 파일을 참조하는 `
59 |
60 |
61 |
62 |