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22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
Table	of	Contents

Introduction

Your	first	application

Get	the	SDK

Hello	World	in	C#

Create	an	ASP.NET	Core	project

MVC	basics

Create	a	controller

Create	models

Create	a	view

Add	a	service	class

Use	dependency	injection

Finish	the	controller

Update	the	layout

Add	external	packages

Use	a	database

Connect	to	a	database

Update	the	context

Create	a	migration

Create	a	new	service	class

Add	more	features

Add	new	to-do	items

Complete	items	with	a	checkbox

Security	and	identity

1.1

1.2

1.2.1

1.2.2

1.2.3

1.3

1.3.1

1.3.2

1.3.3

1.3.4

1.3.5

1.3.6

1.3.7

1.4

1.5

1.5.1

1.5.2

1.5.3

1.5.4

1.6

1.6.1

1.6.2

1.7

2

Require	authentication

Using	identity	in	the	application

Authorization	with	roles

More	resources

Automated	testing

Unit	testing

Integration	testing

Deploy	the	application

Deploy	to	Azure

Deploy	with	Docker

Conclusion

1.7.1

1.7.2

1.7.3

1.7.4

1.8

1.8.1

1.8.2

1.9

1.9.1

1.9.2

1.10

3

Introduction

The	Little	ASP.NET	Core	Book

by	Nate	Barbettini

Copyright	©	2018.	All	rights	reserved.

ISBN:	978-1-387-75615-5

Released	under	the	Creative	Commons	Attribution	4.0	license.	You	are

free	to	share,	copy,	and	redistribute	this	book	in	any	format,	or	remix	and

transform	it	for	any	purpose	(even	commercially).	You	must	give

appropriate	credit	and	provide	a	link	to	the	license.

For	more	information,	visit

https://creativecommons.org/licenses/by/4.0/

Introduction

Thanks	for	picking	up	The	Little	ASP.NET	Core	Book!	I	wrote	this	short

book	to	help	developers	and	people	interested	in	web	programming

learn	about	ASP.NET	Core,	a	new	framework	for	building	web

applications	and	APIs.

The	Little	ASP.NET	Core	Book	is	structured	as	a	tutorial.	You'll	build	an

application	from	start	to	finish	and	learn:

The	basics	of	the	MVC	(Model-View-Controller)	pattern

How	front-end	code	(HTML,	CSS,	JavaScript)	works	together	with

back-end	code

What	dependency	injection	is	and	why	it's	useful

How	to	read	and	write	data	to	a	database

How	to	add	log-in,	registration,	and	security

How	to	deploy	the	application	to	the	web

4

Introduction

Don't	worry,	you	don't	need	to	know	anything	about	ASP.NET	Core	(or

any	of	the	above)	to	get	started.

Before	you	begin

The	code	for	the	finished	version	of	the	application	you'll	build	is

available	on	GitHub:

https://www.github.com/nbarbettini/little-aspnetcore-todo

Feel	free	to	download	it	if	you	want	to	see	the	finished	product,	or

compare	as	you	write	your	own	code.

The	book	itself	is	updated	frequently	with	bug	fixes	and	new	content.	If

you're	reading	a	PDF,	e-book,	or	print	version,	check	the	official	website

(littleasp.net/book)	to	see	if	there's	an	updated	version	available.	The

very	last	page	of	the	book	contains	version	information	and	a	changelog.

Reading	in	your	own	language

Thanks	to	some	fantastic	multilingual	contributors,	the	Little	ASP.NET

Core	Book	has	been	translated	into	other	languages:

Turkish:	https://sahinyanlik.gitbooks.io/kisa-asp-net-core-kitabi/

Chinese:	https://windsting.github.io/little-aspnetcore-book/book/

Who	this	book	is	for

If	you're	new	to	programming,	this	book	will	introduce	you	to	the

patterns	and	concepts	used	to	build	modern	web	applications.	You'll

learn	how	to	build	a	web	app	(and	how	the	big	pieces	fit	together)	by

5

Introduction

building	something	from	scratch!	While	this	little	book	won't	be	able	to

cover	absolutely	everything	you	need	to	know	about	programming,	it'll

give	you	a	starting	point	so	you	can	learn	more	advanced	topics.

If	you	already	code	in	a	backend	language	like	Node,	Python,	Ruby,	Go,

or	Java,	you'll	notice	a	lot	of	familiar	ideas	like	MVC,	view	templates,	and

dependency	injection.	The	code	will	be	in	C#,	but	it	won't	look	too

different	from	what	you	already	know.

If	you're	an	ASP.NET	MVC	developer,	you'll	feel	right	at	home!	ASP.NET

Core	adds	some	new	tools	and	reuses	(and	simplifies)	the	things	you

already	know.	I'll	point	out	some	of	the	differences	below.

No	matter	what	your	previous	experience	with	web	programming,	this

book	will	teach	you	everything	you	need	to	create	a	simple	and	useful

web	application	in	ASP.NET	Core.	You'll	learn	how	to	build	functionality

using	backend	and	frontend	code,	how	to	interact	with	a	database,	and

how	to	deploy	the	app	to	the	world.

What	is	ASP.NET	Core?

ASP.NET	Core	is	a	web	framework	created	by	Microsoft	for	building	web

applications,	APIs,	and	microservices.	It	uses	common	patterns	like	MVC

(Model-View-Controller),	dependency	injection,	and	a	request	pipeline

comprised	of	middleware.	It's	open-source	under	the	Apache	2.0	license,

which	means	the	source	code	is	freely	available,	and	the	community	is

encouraged	to	contribute	bug	fixes	and	new	features.

ASP.NET	Core	runs	on	top	of	Microsoft's	.NET	runtime,	similar	to	the

Java	Virtual	Machine	(JVM)	or	the	Ruby	interpreter.	You	can	write

ASP.NET	Core	applications	in	a	number	of	languages	(C#,	Visual	Basic,

F#).	C#	is	the	most	popular	choice,	and	it's	what	I'll	use	in	this	book.	You

can	build	and	run	ASP.NET	Core	applications	on	Windows,	Mac,	and

Linux.

6

Introduction

Why	do	we	need	another	web
framework?

There	are	a	lot	of	great	web	frameworks	to	choose	from	already:

Node/Express,	Spring,	Ruby	on	Rails,	Django,	Laravel,	and	many	more.

What	advantages	does	ASP.NET	Core	have?

Speed.	ASP.NET	Core	is	fast.	Because	.NET	code	is	compiled,	it

executes	much	faster	than	code	in	interpreted	languages	like

JavaScript	or	Ruby.	ASP.NET	Core	is	also	optimized	for

multithreading	and	asynchronous	tasks.	It's	common	to	see	a	5-10x

speed	improvement	over	code	written	in	Node.js.

Ecosystem.	ASP.NET	Core	may	be	new,	but	.NET	has	been	around

for	a	long	time.	There	are	thousands	of	packages	available	on	NuGet

(the	.NET	package	manager;	think	npm,	Ruby	gems,	or	Maven).

There	are	already	packages	available	for	JSON	deserialization,

database	connectors,	PDF	generation,	or	almost	anything	else	you

can	think	of.

Security.	The	team	at	Microsoft	takes	security	seriously,	and

ASP.NET	Core	is	built	to	be	secure	from	the	ground	up.	It	handles

things	like	sanitizing	input	data	and	preventing	cross-site	request

forgery	(CSRF)	attacks,	so	you	don't	have	to.	You	also	get	the

benefit	of	static	typing	with	the	.NET	compiler,	which	is	like	having	a

very	paranoid	linter	turned	on	at	all	times.	This	makes	it	harder	to	do

something	you	didn't	intend	with	a	variable	or	chunk	of	data.

.NET	Core	and	.NET	Standard

Throughout	this	book,	you'll	be	learning	about	ASP.NET	Core	(the	web

framework).	I'll	occasionally	mention	the	.NET	runtime,	the	supporting

library	that	runs	.NET	code.	If	this	already	sounds	like	Greek	to	you,	just

7

Introduction

skip	to	the	next	chapter!

You	may	also	hear	about	.NET	Core	and	.NET	Standard.	The	naming	gets

confusing,	so	here's	a	simple	explanation:

.NET	Standard	is	a	platform-agnostic	interface	that	defines	features	and

APIs.	It's	important	to	note	that	.NET	Standard	doesn't	represent	any

actual	code	or	functionality,	just	the	API	definition.	There	are	different

"versions"	or	levels	of	.NET	Standard	that	reflect	how	many	APIs	are

available	(or	how	wide	the	API	surface	area	is).	For	example,	.NET

Standard	2.0	has	more	APIs	available	than	.NET	Standard	1.5,	which	has

more	APIs	than	.NET	Standard	1.0.

.NET	Core	is	the	.NET	runtime	that	can	be	installed	on	Windows,	Mac,	or

Linux.	It	implements	the	APIs	defined	in	the	.NET	Standard	interface	with

the	appropriate	platform-specific	code	on	each	operating	system.	This	is

what	you'll	install	on	your	own	machine	to	build	and	run	ASP.NET	Core

applications.

And	just	for	good	measure,	.NET	Framework	is	a	different

implementation	of	.NET	Standard	that	is	Windows-only.	This	was	the

only	.NET	runtime	until	.NET	Core	came	along	and	brought	.NET	to	Mac

and	Linux.	ASP.NET	Core	can	also	run	on	Windows-only	.NET

Framework,	but	I	won't	touch	on	this	too	much.

If	you're	confused	by	all	this	naming,	no	worries!	We'll	get	to	some	real

code	in	a	bit.

A	note	to	ASP.NET	4	developers

If	you	haven't	used	a	previous	version	of	ASP.NET,	skip	ahead	to	the

next	chapter.

8

Introduction

ASP.NET	Core	is	a	complete	ground-up	rewrite	of	ASP.NET,	with	a	focus

on	modernizing	the	framework	and	finally	decoupling	it	from

System.Web,	IIS,	and	Windows.	If	you	remember	all	the	OWIN/Katana

stuff	from	ASP.NET	4,	you're	already	halfway	there:	the	Katana	project

became	ASP.NET	5	which	was	ultimately	renamed	to	ASP.NET	Core.

Because	of	the	Katana	legacy,	the	 	Startup		class	is	front	and	center,	and

there's	no	more	 	Application_Start		or	 	Global.asax	.	The	entire	pipeline

is	driven	by	middleware,	and	there's	no	longer	a	split	between	MVC	and

Web	API:	controllers	can	simply	return	views,	status	codes,	or	data.

Dependency	injection	comes	baked	in,	so	you	don't	need	to	install	and

configure	a	container	like	StructureMap	or	Ninject	if	you	don't	want	to.

And	the	entire	framework	has	been	optimized	for	speed	and	runtime

efficiency.

Alright,	enough	introduction.	Let's	dive	in	to	ASP.NET	Core!

9

Your	first	application

Your	first	application

Ready	to	build	your	first	web	app	with	ASP.NET	Core?	You'll	need	to

gather	a	few	things	first:

Your	favorite	code	editor.	You	can	use	Atom,	Sublime,	Notepad,	or

whatever	editor	you	prefer	writing	code	in.	If	you	don't	have	a	favorite,

give	Visual	Studio	Code	a	try.	It's	a	free,	cross-platform	code	editor	that

has	rich	support	for	writing	C#,	JavaScript,	HTML,	and	more.	Just	search

for	"download	visual	studio	code"	and	follow	the	instructions.

If	you're	on	Windows,	you	can	also	use	Visual	Studio	to	build	ASP.NET

Core	applications.	You'll	need	Visual	Studio	2017	version	15.3	or	later

(the	free	Community	Edition	is	fine).	Visual	Studio	has	great	code

completion	and	refactoring	support	for	C#,	although	Visual	Studio	Code

is	close	behind.

The	.NET	Core	SDK.	Regardless	of	the	editor	or	platform	you're	using,

you'll	need	to	install	the	.NET	Core	SDK,	which	includes	the	runtime,

base	libraries,	and	command	line	tools	you	need	for	building	ASP.NET

Core	applications.	The	SDK	can	be	installed	on	Windows,	Mac,	or	Linux.

Once	you've	decided	on	an	editor,	you'll	need	to	get	the	SDK.

10

Get	the	SDK

Get	the	SDK

Search	for	"download	.net	core"	and	follow	the	instructions	on

Microsoft's	download	page	to	get	the	.NET	Core	SDK.	After	the	SDK	has

finished	installing,	open	up	the	Terminal	(or	PowerShell	on	Windows)	and

use	the	 	dotnet		command	line	tool	(also	called	a	CLI)	to	make	sure

everything	is	working:

dotnet	--version

2.1.104

You	can	get	more	information	about	your	platform	with	the	 	--info		flag:

dotnet	--info

.NET	Command	Line	Tools	(2.1.104)

Product	Information:

	Version:												2.1.104

	Commit	SHA-1	hash:		48ec687460

Runtime	Environment:

	OS	Name:					Mac	OS	X

	OS	Version:		10.13

(more	details...)

If	you	see	output	like	the	above,	you're	ready	to	go!

11

Hello	World	in	C#

Hello	World	in	C#

Before	you	dive	into	ASP.NET	Core,	try	creating	and	running	a	simple	C#

application.

You	can	do	this	all	from	the	command	line.	First,	open	up	the	Terminal

(or	PowerShell	on	Windows).	Navigate	to	the	location	you	want	to	store

your	projects,	such	as	your	Documents	directory:

cd	Documents

Use	the	 	dotnet		command	to	create	a	new	project:

dotnet	new	console	-o	CsharpHelloWorld

The	 	dotnet	new		command	creates	a	new	.NET	project	in	C#	by	default.

The	 	console		parameter	selects	a	template	for	a	console	application	(a

program	that	outputs	text	to	the	screen).	The	 	-o	CsharpHelloWorld	

parameter	tells	 	dotnet	new		to	create	a	new	directory	called

	CsharpHelloWorld		for	all	the	project	files.	Move	into	this	new	directory:

cd	CsharpHelloWorld

	dotnet	new	console		creates	a	basic	C#	program	that	writes	the	text

	Hello	World!		to	the	screen.	The	program	is	comprised	of	two	files:	a

project	file	(with	a	 	.csproj		extension)	and	a	C#	code	file	(with	a	 	.cs	

extension).	If	you	open	the	former	in	a	text	or	code	editor,	you'll	see	this:

CsharpHelloWorld.csproj

<Project	Sdk="Microsoft.NET.Sdk">

12

Hello	World	in	C#

		<PropertyGroup>

				<OutputType>Exe</OutputType>

				<TargetFramework>netcoreapp2.0</TargetFramework>

		</PropertyGroup>

</Project>

The	project	file	is	XML-based	and	defines	some	metadata	about	the

project.	Later,	when	you	reference	other	packages,	those	will	be	listed

here	(similar	to	a	 	package.json		file	for	npm).	You	won't	have	to	edit	this

file	by	hand	very	often.

Program.cs

using	System;

namespace	CsharpHelloWorld

{

				class	Program

				{

								static	void	Main(string[]	args)

								{

												Console.WriteLine("Hello	World!");

								}

				}

}

	static	void	Main		is	the	entry	point	method	of	a	C#	program,	and	by

convention	it's	placed	in	a	class	(a	type	of	code	structure	or	module)

called	 	Program	.	The	 	using		statement	at	the	top	imports	the	built-in

	System		classes	from	.NET	and	makes	them	available	to	the	code	in	your

class.

From	inside	the	project	directory,	use	 	dotnet	run		to	run	the	program.

You'll	see	the	output	written	to	the	console	after	the	code	compiles:

dotnet	run

13

Hello	World	in	C#

Hello	World!

That's	all	it	takes	to	scaffold	and	run	a	.NET	program!	Next,	you'll	do	the

same	thing	for	an	ASP.NET	Core	application.

14

Create	an	ASP.NET	Core	project

Create	an	ASP.NET	Core	project

If	you're	still	in	the	directory	you	created	for	the	Hello	World	sample,

move	back	up	to	your	Documents	or	home	directory:

cd	..

Next,	create	a	new	directory	to	store	your	entire	project,	and	move	into

it:

mkdir	AspNetCoreTodo

cd	AspNetCoreTodo

Next,	create	a	new	project	with	 	dotnet	new	,	this	time	with	some	extra

options:

dotnet	new	mvc	--auth	Individual	-o	AspNetCoreTodo

cd	AspNetCoreTodo

This	creates	a	new	project	from	the	 	mvc		template,	and	adds	some

additional	authentication	and	security	bits	to	the	project.	(I'll	cover

security	in	the	Security	and	identity	chapter.)

You	might	be	wondering	why	you	have	a	directory	called

	AspNetCoreTodo		inside	another	directory	called	 	AspNetCoreTodo	.

The	top-level	or	"root"	directory	can	contain	one	or	more	project

directories.	The	root	directory	is	sometimes	called	a	solution

directory.	Later,	you'll	add	more	project	directories	side-by-side

with	the	 	AspNetCoreTodo		project	directory,	all	within	a	single	root

solution	directory.

15

Create	an	ASP.NET	Core	project

You'll	see	quite	a	few	files	show	up	in	the	new	project	directory.	Once

you	 	cd		into	the	new	directory,	all	you	have	to	do	is	run	the	project:

dotnet	run

Now	listening	on:	http://localhost:5000

Application	started.	Press	Ctrl+C	to	shut	down.

Instead	of	printing	to	the	console	and	exiting,	this	program	starts	a	web

server	and	waits	for	requests	on	port	5000.

Open	your	web	browser	and	navigate	to	 	http://localhost:5000	.	You'll

see	the	default	ASP.NET	Core	splash	page,	which	means	your	project	is

working!	When	you're	done,	press	Ctrl-C	in	the	terminal	window	to	stop

the	server.

The	parts	of	an	ASP.NET	Core	project

The	 	dotnet	new	mvc		template	generates	a	number	of	files	and

directories	for	you.	Here	are	the	most	important	things	you	get	out	of

the	box:

The	Program.cs	and	Startup.cs	files	set	up	the	web	server	and

ASP.NET	Core	pipeline.	The	 	Startup		class	is	where	you	can	add

middleware	that	handles	and	modifies	incoming	requests,	and	serves

things	like	static	content	or	error	pages.	It's	also	where	you	add	your

own	services	to	the	dependency	injection	container	(more	on	this

later).

The	Models,	Views,	and	Controllers	directories	contain	the

components	of	the	Model-View-Controller	(MVC)	architecture.

You'll	explore	all	three	in	the	next	chapter.

16

Create	an	ASP.NET	Core	project

The	wwwroot	directory	contains	static	assets	like	CSS,	JavaScript,

and	image	files.	Files	in	 	wwwroot		will	be	served	as	static	content,

and	can	be	bundled	and	minified	automatically.

The	appsettings.json	file	contains	configuration	settings	ASP.NET

Core	will	load	on	startup.	You	can	use	this	to	store	database

connection	strings	or	other	things	that	you	don't	want	to	hard-code.

Tips	for	Visual	Studio	Code

If	you're	using	Visual	Studio	Code	for	the	first	time,	here	are	a	couple	of

helpful	tips	to	get	you	started:

Open	the	project	root	folder:	In	Visual	Studio	Code,	choose	File	-

Open	or	File	-	Open	Folder.	Open	the	 	AspNetCoreTodo		folder	(the

root	directory),	not	the	inner	project	directory.	If	Visual	Studio	Code

prompts	you	to	install	missing	files,	click	Yes	to	add	them.

F5	to	run	(and	debug	breakpoints):	With	your	project	open,	press	F5

to	run	the	project	in	debug	mode.	This	is	the	same	as	 	dotnet	run	

on	the	command	line,	but	you	have	the	benefit	of	setting

breakpoints	in	your	code	by	clicking	on	the	left	margin:

Lightbulb	to	fix	problems:	If	your	code	contains	red	squiggles

(compiler	errors),	put	your	cursor	on	the	code	that's	red	and	look	for

the	lightbulb	icon	on	the	left	margin.	The	lightbulb	menu	will	suggest

17

Create	an	ASP.NET	Core	project

common	fixes,	like	adding	a	missing	 	using		statement	to	your	code:

Compile	quickly:	Use	the	shortcut	 	Command-Shift-B		or	 	Control-

Shift-B		to	run	the	Build	task,	which	does	the	same	thing	as	 	dotnet

build	.

These	tips	apply	to	Visual	Studio	(not	Code)	on	Windows	too.	If

you're	using	Visual	Studio,	you'll	need	to	open	the	 	.csproj	

project	file	directly.	Visual	Studio	will	later	prompt	you	to	save	the

Solution	file,	which	you	should	save	in	the	root	directory	(the	first

	AspNetCoreTodo		folder).	You	can	also	create	an	ASP.NET	Core

project	directly	within	Visual	Studio	using	the	templates	in	File	-

New	Project.

A	note	about	Git

If	you	use	Git	or	GitHub	to	manage	your	source	code,	now	is	a	good	time

to	do	 	git	init		and	initialize	a	Git	repository	in	the	project	root

directory:

cd	..

git	init

Make	sure	you	add	a	 	.gitignore		file	that	ignores	the	 	bin		and	 	obj	

directories.	The	Visual	Studio	template	on	GitHub's	gitignore	template

repo	(https://github.com/github/gitignore)	works	great.

18

Create	an	ASP.NET	Core	project

There's	plenty	more	to	explore,	so	let's	dive	in	and	start	building	an

application!

19

MVC	basics

MVC	basics

In	this	chapter,	you'll	explore	the	MVC	system	in	ASP.NET	Core.	MVC

(Model-View-Controller)	is	a	pattern	for	building	web	applications	that's

used	in	almost	every	web	framework	(Ruby	on	Rails	and	Express	are

popular	examples),	plus	frontend	JavaScript	frameworks	like	Angular.

Mobile	apps	on	iOS	and	Android	use	a	variation	of	MVC	as	well.

As	the	name	suggests,	MVC	has	three	components:	models,	views,	and

controllers.	Controllers	handle	incoming	requests	from	a	client	or	web

browser	and	make	decisions	about	what	code	to	run.	Views	are

templates	(usually	HTML	plus	a	templating	language	like	Handlebars,

Pug,	or	Razor)	that	get	data	added	to	them	and	then	are	displayed	to	the

user.	Models	hold	the	data	that	is	added	to	views,	or	data	that	is	entered

by	the	user.

A	common	pattern	for	MVC	code	is:

The	controller	receives	a	request	and	looks	up	some	information	in	a

database

The	controller	creates	a	model	with	the	information	and	attaches	it

to	a	view

The	view	is	rendered	and	displayed	in	the	user's	browser

The	user	clicks	a	button	or	submits	a	form,	which	sends	a	new

request	to	the	controller,	and	the	cycle	repeats

If	you've	worked	with	MVC	in	other	languages,	you'll	feel	right	at	home

in	ASP.NET	Core	MVC.	If	you're	new	to	MVC,	this	chapter	will	teach	you

the	basics	and	will	help	get	you	started.

What	you'll	build

20

MVC	basics

The	"Hello	World"	exercise	of	MVC	is	building	a	to-do	list	application.	It's

a	great	project	since	it's	small	and	simple	in	scope,	but	it	touches	each

part	of	MVC	and	covers	many	of	the	concepts	you'd	use	in	a	larger

application.

In	this	book,	you'll	build	a	to-do	app	that	lets	the	user	add	items	to	their

to-do	list	and	check	them	off	once	complete.	More	specifically,	you'll	be

creating:

A	web	application	server	(sometimes	called	the	"backend")	using

ASP.NET	Core,	C#,	and	the	MVC	pattern

A	database	to	store	the	user's	to-do	items	using	the	SQLite	database

engine	and	a	system	called	Entity	Framework	Core

Web	pages	and	an	interface	that	the	user	will	interact	with	via	their

browser,	using	HTML,	CSS,	and	JavaScript	(called	the	"frontend")

A	login	form	and	security	checks	so	each	user's	to-do	list	is	kept

private

Sound	good?	Let's	built	it!	If	you	haven't	already	created	a	new	ASP.NET

Core	project	using	 	dotnet	new	mvc	,	follow	the	steps	in	the	previous

chapter.	You	should	be	able	to	build	and	run	the	project	and	see	the

default	welcome	screen.

21

Create	a	controller

Create	a	controller

There	are	already	a	few	controllers	in	the	project's	Controllers	directory,

including	the	 	HomeController		that	renders	the	default	welcome	screen

you	see	when	you	visit	 	http://localhost:5000	.	You	can	ignore	these

controllers	for	now.

Create	a	new	controller	for	the	to-do	list	functionality,	called

	TodoController	,	and	add	the	following	code:

Controllers/TodoController.cs

using	System;

using	System.Collections.Generic;

using	System.Linq;

using	System.Threading.Tasks;

using	Microsoft.AspNetCore.Mvc;

namespace	AspNetCoreTodo.Controllers

{

				public	class	TodoController	:	Controller

				{

								//	Actions	go	here

				}

}

Routes	that	are	handled	by	controllers	are	called	actions,	and	are

represented	by	methods	in	the	controller	class.	For	example,	the

	HomeController		includes	three	action	methods	( 	Index	,	 	About	,	and

	Contact	)	which	are	mapped	by	ASP.NET	Core	to	these	route	URLs:

localhost:5000/Home									->	Index()

localhost:5000/Home/About			->	About()

localhost:5000/Home/Contact	->	Contact()

22

Create	a	controller

There	are	a	number	of	conventions	(common	patterns)	used	by	ASP.NET

Core,	such	as	the	pattern	that	 	FooController		becomes	 	/Foo	,	and	the

	Index		action	name	can	be	left	out	of	the	URL.	You	can	customize	this

behavior	if	you'd	like,	but	for	now,	we'll	stick	to	the	default	conventions.

Add	a	new	action	called	 	Index		to	the	 	TodoController	,	replacing	the	 	//

Actions	go	here		comment:

public	class	TodoController	:	Controller

{

				public	IActionResult	Index()

				{

								//	Get	to-do	items	from	database

								//	Put	items	into	a	model

								//	Render	view	using	the	model

				}

}

Action	methods	can	return	views,	JSON	data,	or	HTTP	status	codes	like

	200	OK		and	 	404	Not	Found	.	The	 	IActionResult		return	type	gives	you

the	flexibility	to	return	any	of	these	from	the	action.

It's	a	best	practice	to	keep	controllers	as	lightweight	as	possible.	In	this

case,	the	controller	will	be	responsible	for	getting	the	to-do	items	from

the	database,	putting	those	items	into	a	model	the	view	can	understand,

and	sending	the	view	back	to	the	user's	browser.

Before	you	can	write	the	rest	of	the	controller	code,	you	need	to	create	a

model	and	a	view.

23

Create	models

Create	models

There	are	two	separate	model	classes	that	need	to	be	created:	a	model

that	represents	a	to-do	item	stored	in	the	database	(sometimes	called	an

entity),	and	the	model	that	will	be	combined	with	a	view	(the	MV	in

MVC)	and	sent	back	to	the	user's	browser.	Because	both	of	them	can	be

referred	to	as	"models",	I'll	refer	to	the	latter	as	a	view	model.

First,	create	a	class	called	 	TodoItem		in	the	Models	directory:

Models/TodoItem.cs

using	System;

using	System.ComponentModel.DataAnnotations;

namespace	AspNetCoreTodo.Models

{

				public	class	TodoItem

				{

								public	Guid	Id	{	get;	set;	}

								public	bool	IsDone	{	get;	set;	}

								[Required]

								public	string	Title	{	get;	set;	}

								public	DateTimeOffset?	DueAt	{	get;	set;	}

				}

}

This	class	defines	what	the	database	will	need	to	store	for	each	to-do

item:	an	ID,	a	title	or	name,	whether	the	item	is	complete,	and	what	the

due	date	is.	Each	line	defines	a	property	of	the	class:

24

Create	models

The	Id	property	is	a	guid,	or	a	globally	unique	identifier.	Guids	(or

GUIDs)	are	long	strings	of	letters	and	numbers,	like	 	43ec09f2-7f70-

4f4b-9559-65011d5781bb	.	Because	guids	are	random	and	are

extremely	unlikely	to	be	accidentally	duplicated,	they	are	commonly

used	as	unique	IDs.	You	could	also	use	a	number	(integer)	as	a

database	entity	ID,	but	you'd	need	to	configure	your	database	to

always	increment	the	number	when	new	rows	are	added	to	the

database.	Guids	are	generated	randomly,	so	you	don't	have	to	worry

about	auto-incrementing.

The	IsDone	property	is	a	boolean	(true/false	value).	By	default,	it

will	be	 	false		for	all	new	items.	Later	you'll	use	write	code	to	switch

this	property	to	 	true		when	the	user	clicks	an	item's	checkbox	in

the	view.

The	Title	property	is	a	string	(text	value).	This	will	hold	the	name	or

description	of	the	to-do	item.	The	 	[Required]		attribute	tells

ASP.NET	Core	that	this	string	can't	be	null	or	empty.

The	DueAt	property	is	a	 	DateTimeOffset	,	which	is	a	C#	type	that

stores	a	date/time	stamp	along	with	a	timezone	offset	from	UTC.

Storing	the	date,	time,	and	timezone	offset	together	makes	it	easy	to

render	dates	accurately	on	systems	in	different	timezones.

Notice	the	 	?		question	mark	after	the	 	DateTimeOffset		type?	That	marks

the	DueAt	property	as	nullable,	or	optional.	If	the	 	?		wasn't	included,

every	to-do	item	would	need	to	have	a	due	date.	The	 	Id		and	 	IsDone	

properties	aren't	marked	as	nullable,	so	they	are	required	and	will	always

have	a	value	(or	a	default	value).

Strings	in	C#	are	always	nullable,	so	there's	no	need	to	mark	the

Title	property	as	nullable.	C#	strings	can	be	null,	empty,	or	contain

text.

25

Create	models

Each	property	is	followed	by	 	get;	set;	,	which	is	a	shorthand	way	of

saying	the	property	is	read/write	(or,	more	technically,	it	has	a	getter	and

setter	methods).

At	this	point,	it	doesn't	matter	what	the	underlying	database	technology

is.	It	could	be	SQL	Server,	MySQL,	MongoDB,	Redis,	or	something	more

exotic.	This	model	defines	what	the	database	row	or	entry	will	look	like

in	C#	so	you	don't	have	to	worry	about	the	low-level	database	stuff	in

your	code.	This	simple	style	of	model	is	sometimes	called	a	"plain	old	C#

object"	or	POCO.

The	view	model

Often,	the	model	(entity)	you	store	in	the	database	is	similar	but	not

exactly	the	same	as	the	model	you	want	to	use	in	MVC	(the	view	model).

In	this	case,	the	 	TodoItem		model	represents	a	single	item	in	the

database,	but	the	view	might	need	to	display	two,	ten,	or	a	hundred	to-

do	items	(depending	on	how	badly	the	user	is	procrastinating).

Because	of	this,	the	view	model	should	be	a	separate	class	that	holds	an

array	of	 	TodoItem	s:

Models/TodoViewModel.cs

namespace	AspNetCoreTodo.Models

{

				public	class	TodoViewModel

				{

								public	TodoItem[]	Items	{	get;	set;	}

				}

}

Now	that	you	have	some	models,	it's	time	to	create	a	view	that	will	take

a	 	TodoViewModel		and	render	the	right	HTML	to	show	the	user	their	to-

do	list.

26

Create	models

27

Create	a	view

Create	a	view

Views	in	ASP.NET	Core	are	built	using	the	Razor	templating	language,

which	combines	HTML	and	C#	code.	(If	you've	written	pages	using

Handlebars	moustaches,	ERB	in	Ruby	on	Rails,	or	Thymeleaf	in	Java,

you've	already	got	the	basic	idea.)

Most	view	code	is	just	HTML,	with	the	occasional	C#	statement	added	in

to	pull	data	out	of	the	view	model	and	turn	it	into	text	or	HTML.	The	C#

statements	are	prefixed	with	the	 	@		symbol.

The	view	rendered	by	the	 	Index		action	of	the	 	TodoController		needs	to

take	the	data	in	the	view	model	(a	sequence	of	to-do	items)	and	display	it

in	a	nice	table	for	the	user.	By	convention,	views	are	placed	in	the

	Views		directory,	in	a	subdirectory	corresponding	to	the	controller	name.

The	file	name	of	the	view	is	the	name	of	the	action	with	a	 	.cshtml	

extension.

Create	a	 	Todo		directory	inside	the	 	Views		directory,	and	add	this	file:

Views/Todo/Index.cshtml

@model	TodoViewModel

@{

				ViewData["Title"]	=	"Manage	your	todo	list";

}

<div	class="panel	panel-default	todo-panel">

		<div	class="panel-heading">@ViewData["Title"]</div>

		<table	class="table	table-hover">

						<thead>

										<tr>

														<td>&#x2714;</td>

														<td>Item</td>

														<td>Due</td>

28

Create	a	view

										</tr>

						</thead>

						@foreach	(var	item	in	Model.Items)

						{

										<tr>

														<td>

																<input	type="checkbox"	class="done-checkbox">

														</td>

														<td>@item.Title</td>

														<td>@item.DueAt</td>

										</tr>

						}

		</table>

		<div	class="panel-footer	add-item-form">

				<!--	TODO:	Add	item	form	-->

		</div>

</div>

At	the	very	top	of	the	file,	the	 	@model		directive	tells	Razor	which	model

to	expect	this	view	to	be	bound	to.	The	model	is	accessed	through	the

	Model		property.

Assuming	there	are	any	to-do	items	in	 	Model.Items	,	the	 	foreach	

statement	will	loop	over	each	to-do	item	and	render	a	table	row	( 	<tr>	

element)	containing	the	item's	name	and	due	date.	A	checkbox	is	also

rendered	that	will	let	the	user	mark	the	item	as	complete.

The	layout	file

You	might	be	wondering	where	the	rest	of	the	HTML	is:	what	about	the

	<body>		tag,	or	the	header	and	footer	of	the	page?	ASP.NET	Core	uses	a

layout	view	that	defines	the	base	structure	that	every	other	view	is

rendered	inside	of.	It's	stored	in	 	Views/Shared/_Layout.cshtml	.

29

Create	a	view

The	default	ASP.NET	Core	template	includes	Bootstrap	and	jQuery	in

this	layout	file,	so	you	can	quickly	create	a	web	application.	Of	course,

you	can	use	your	own	CSS	and	JavaScript	libraries	if	you'd	like.

Customizing	the	stylesheet

The	default	template	also	includes	a	stylesheet	with	some	basic	CSS

rules.	The	stylesheet	is	stored	in	the	 	wwwroot/css		directory.	Add	a	few

new	CSS	style	rules	to	the	bottom	of	the	 	site.css		file:

wwwroot/css/site.css

div.todo-panel	{

		margin-top:	15px;

}

table	tr.done	{

		text-decoration:	line-through;

		color:	#888;

}

You	can	use	CSS	rules	like	these	to	completely	customize	how	your

pages	look	and	feel.

ASP.NET	Core	and	Razor	can	do	much	more,	such	as	partial	views	and

server-rendered	view	components,	but	a	simple	layout	and	view	is	all

you	need	for	now.	The	official	ASP.NET	Core	documentation	(at

https://docs.asp.net)	contains	a	number	of	examples	if	you'd	like	to	learn

more.

30

Add	a	service	class

Add	a	service	class

You've	created	a	model,	a	view,	and	a	controller.	Before	you	use	the

model	and	view	in	the	controller,	you	also	need	to	write	code	that	will

get	the	user's	to-do	items	from	a	database.

You	could	write	this	database	code	directly	in	the	controller,	but	it's	a

better	practice	to	keep	your	code	separate.	Why?	In	a	big,	real-world

application,	you'll	have	to	juggle	many	concerns:

Rendering	views	and	handling	incoming	data:	this	is	what	your

controller	already	does.

Performing	business	logic,	or	code	and	logic	that's	related	to	the

purpose	and	"business"	of	your	application.	In	a	to-do	list

application,	business	logic	means	decisions	like	setting	a	default	due

date	on	new	tasks,	or	only	displaying	tasks	that	are	incomplete.

Other	examples	of	business	logic	include	calculating	a	total	cost

based	on	product	prices	and	tax	rates,	or	checking	whether	a	player

has	enough	points	to	level	up	in	a	game.

Saving	and	retrieving	items	from	a	database.

Again,	it's	possible	to	do	all	of	these	things	in	a	single,	massive	controller,

but	that	quickly	becomes	too	hard	to	manage	and	test.	Instead,	it's

common	to	see	applications	split	up	into	two,	three,	or	more	"layers"	or

tiers	that	each	handle	one	(and	only	one)	concern.	This	helps	keep	the

controllers	as	simple	as	possible,	and	makes	it	easier	to	test	and	change

the	business	logic	and	database	code	later.

Separating	your	application	this	way	is	sometimes	called	a	multi-tier	or

n-tier	architecture.	In	some	cases,	the	tiers	(layers)	are	isolated	in

completely	separate	projects,	but	other	times	it	just	refers	to	how	the

31

Add	a	service	class

classes	are	organized	and	used.	The	important	thing	is	thinking	about

how	to	split	your	application	into	manageable	pieces,	and	avoid	having

controllers	or	bloated	classes	that	try	to	do	everything.

For	this	project,	you'll	use	two	application	layers:	a	presentation	layer

made	up	of	the	controllers	and	views	that	interact	with	the	user,	and	a

service	layer	that	contains	business	logic	and	database	code.	The

presentation	layer	already	exists,	so	the	next	step	is	to	build	a	service

that	handles	to-do	business	logic	and	saves	to-do	items	to	a	database.

Most	larger	projects	use	a	3-tier	architecture:	a	presentation	layer,

a	service	logic	layer,	and	a	data	repository	layer.	A	repository	is	a

class	that's	only	focused	on	database	code	(no	business	logic).	In

this	application,	you'll	combine	these	into	a	single	service	layer	for

simplicity,	but	feel	free	to	experiment	with	different	ways	of

architecting	the	code.

Create	an	interface

The	C#	language	includes	the	concept	of	interfaces,	where	the	definition

of	an	object's	methods	and	properties	is	separate	from	the	class	that

actually	contains	the	code	for	those	methods	and	properties.	Interfaces

make	it	easy	to	keep	your	classes	decoupled	and	easy	to	test,	as	you'll

see	here	(and	later	in	the	Automated	testing	chapter).	You'll	use	an

interface	to	represent	the	service	that	can	interact	with	to-do	items	in

the	database.

By	convention,	interfaces	are	prefixed	with	"I".	Create	a	new	file	in	the

Services	directory:

Services/ITodoItemService.cs

using	System;

using	System.Collections.Generic;

using	System.Threading.Tasks;

using	AspNetCoreTodo.Models;

32

Add	a	service	class

namespace	AspNetCoreTodo.Services

{

				public	interface	ITodoItemService

				{

								Task<TodoItem[]>	GetIncompleteItemsAsync();

				}

}

Note	that	the	namespace	of	this	file	is	 	AspNetCoreTodo.Services	.

Namespaces	are	a	way	to	organize	.NET	code	files,	and	it's	customary	for

the	namespace	to	follow	the	directory	the	file	is	stored	in

( 	AspNetCoreTodo.Services		for	files	in	the	 	Services		directory,	and	so	on).

Because	this	file	(in	the	 	AspNetCoreTodo.Services		namespace)	references

the	 	TodoItem		class	(in	the	 	AspNetCoreTodo.Models		namespace),	it	needs

to	include	a	 	using		statement	at	the	top	of	the	file	to	import	that

namespace.	Without	the	 	using		statement,	you'll	see	an	error	like:

The	type	or	namespace	name	'TodoItem'	could	not	be	found	(are	you	

missing	a	using	directive	or	an	assembly	reference?)

Since	this	is	an	interface,	there	isn't	any	actual	code	here,	just	the

definition	(or	method	signature)	of	the	 	GetIncompleteItemsAsync	

method.	This	method	requires	no	parameters	and	returns	a

	Task<TodoItem[]>	.

If	this	syntax	looks	confusing,	think:	"a	Task	that	contains	an	array

of	TodoItems".

The	 	Task		type	is	similar	to	a	future	or	a	promise,	and	it's	used	here

because	this	method	will	be	asynchronous.	In	other	words,	the	method

may	not	be	able	to	return	the	list	of	to-do	items	right	away	because	it

needs	to	go	talk	to	the	database	first.	(More	on	this	later.)

Create	the	service	class

33

Add	a	service	class

Now	that	the	interface	is	defined,	you're	ready	to	create	the	actual

service	class.	I'll	cover	database	code	in	depth	in	the	Use	a	database

chapter,	so	for	now	you'll	just	fake	it	and	always	return	two	hard-coded

items:

Services/FakeTodoItemService.cs

using	System;

using	System.Collections.Generic;

using	System.Threading.Tasks;

using	AspNetCoreTodo.Models;

namespace	AspNetCoreTodo.Services

{

				public	class	FakeTodoItemService	:	ITodoItemService

				{

								public	Task<TodoItem[]>	GetIncompleteItemsAsync()

								{

												var	item1	=	new	TodoItem

												{

																Title	=	"Learn	ASP.NET	Core",

																DueAt	=	DateTimeOffset.Now.AddDays(1)

												};

												var	item2	=	new	TodoItem

												{

																Title	=	"Build	awesome	apps",

																DueAt	=	DateTimeOffset.Now.AddDays(2)

												};

												return	Task.FromResult(new[]	{	item1,	item2	});

								}

				}

}

This	 	FakeTodoItemService		implements	the	 	ITodoItemService		interface

but	always	returns	the	same	array	of	two	 	TodoItem	s.	You'll	use	this	to

test	the	controller	and	view,	and	then	add	real	database	code	in	Use	a

database.

34

Add	a	service	class

35

Use	dependency	injection

Use	dependency	injection

Back	in	the	 	TodoController	,	add	some	code	to	work	with	the

	ITodoItemService	:

public	class	TodoController	:	Controller

{

				private	readonly	ITodoItemService	_todoItemService;

				public	TodoController(ITodoItemService	todoItemService)

				{

								_todoItemService	=	todoItemService;

				}

				public	IActionResult	Index()

				{

								//	Get	to-do	items	from	database

								//	Put	items	into	a	model

								//	Pass	the	view	to	a	model	and	render

				}

}

Since	 	ITodoItemService		is	in	the	 	Services		namespace,	you'll	also	need

to	add	a	 	using		statement	at	the	top:

using	AspNetCoreTodo.Services;

The	first	line	of	the	class	declares	a	private	variable	to	hold	a	reference	to

the	 	ITodoItemService	.	This	variable	lets	you	use	the	service	from	the

	Index		action	method	later	(you'll	see	how	in	a	minute).

The	 	public	TodoController(ITodoItemService	todoItemService)		line

defines	a	constructor	for	the	class.	The	constructor	is	a	special	method

that	is	called	when	you	want	to	create	a	new	instance	of	a	class	(the

36

Use	dependency	injection

	TodoController		class,	in	this	case).	By	adding	an	 	ITodoItemService	

parameter	to	the	constructor,	you've	declared	that	in	order	to	create	the

	TodoController	,	you'll	need	to	provide	an	object	that	matches	the

	ITodoItemService		interface.

Interfaces	are	awesome	because	they	help	decouple	(separate)	the

logic	of	your	application.	Since	the	controller	depends	on	the

	ITodoItemService		interface,	and	not	on	any	specific	class,	it

doesn't	know	or	care	which	class	it's	actually	given.	It	could	be	the

	FakeTodoItemService	,	a	different	one	that	talks	to	a	live	database,

or	something	else!	As	long	as	it	matches	the	interface,	the

controller	can	use	it.	This	makes	it	really	easy	to	test	parts	of	your

application	separately.	I'll	cover	testing	in	detail	in	the	Automated

testing	chapter.

Now	you	can	finally	use	the	 	ITodoItemService		(via	the	private	variable

you	declared)	in	your	action	method	to	get	to-do	items	from	the	service

layer:

public	IActionResult	Index()

{

				var	items	=	await	_todoItemService.GetIncompleteItemsAsync();

				//	...

}

Remember	that	the	 	GetIncompleteItemsAsync		method	returned	a

	Task<TodoItem[]>	?	Returning	a	 	Task		means	that	the	method	won't

necessarily	have	a	result	right	away,	but	you	can	use	the	 	await		keyword

to	make	sure	your	code	waits	until	the	result	is	ready	before	continuing

on.

The	 	Task		pattern	is	common	when	your	code	calls	out	to	a	database	or

an	API	service,	because	it	won't	be	able	to	return	a	real	result	until	the

database	(or	network)	responds.	If	you've	used	promises	or	callbacks	in

37

Use	dependency	injection

JavaScript	or	other	languages,	 	Task		is	the	same	idea:	the	promise	that

there	will	be	a	result	-	sometime	in	the	future.

If	you've	had	to	deal	with	"callback	hell"	in	older	JavaScript	code,

you're	in	luck.	Dealing	with	asynchronous	code	in	.NET	is	much

easier	thanks	to	the	magic	of	the	 	await		keyword!	 	await		lets

your	code	pause	on	an	async	operation,	and	then	pick	up	where	it

left	off	when	the	underlying	database	or	network	request	finishes.

In	the	meantime,	your	application	isn't	blocked,	because	it	can

process	other	requests	as	needed.	This	pattern	is	simple	but	takes

a	little	getting	used	to,	so	don't	worry	if	this	doesn't	make	sense

right	away.	Just	keep	following	along!

The	only	catch	is	that	you	need	to	update	the	 	Index		method	signature

to	return	a	 	Task<IActionResult>		instead	of	just	 	IActionResult	,	and

mark	it	as	 	async	:

public	async	Task<IActionResult>	Index()

{

				var	items	=	await	_todoItemService.GetIncompleteItemsAsync();

				//	Put	items	into	a	model

				//	Pass	the	view	to	a	model	and	render

}

You're	almost	there!	You've	made	the	 	TodoController		depend	on	the

	ITodoItemService		interface,	but	you	haven't	yet	told	ASP.NET	Core	that

you	want	the	 	FakeTodoItemService		to	be	the	actual	service	that's	used

under	the	hood.	It	might	seem	obvious	right	now	since	you	only	have

one	class	that	implements	 	ITodoItemService	,	but	later	you'll	have

multiple	classes	that	implement	the	same	interface,	so	being	explicit	is

necessary.

38

Use	dependency	injection

Declaring	(or	"wiring	up")	which	concrete	class	to	use	for	each	interface

is	done	in	the	 	ConfigureServices		method	of	the	 	Startup		class.	Right

now,	it	looks	something	like	this:

Startup.cs

public	void	ConfigureServices(IServiceCollection	services)

{

				//	(...	some	code)

				services.AddMvc();

}

The	job	of	the	 	ConfigureServices		method	is	adding	things	to	the	service

container,	or	the	collection	of	services	that	ASP.NET	Core	knows	about.

The	 	services.AddMvc		line	adds	the	services	that	the	internal	ASP.NET

Core	systems	need	(as	an	experiment,	try	commenting	out	this	line).	Any

other	services	you	want	to	use	in	your	application	must	be	added	to	the

service	container	here	in	 	ConfigureServices	.

Add	the	following	line	anywhere	inside	the	 	ConfigureServices		method:

services.AddSingleton<ITodoItemService,	FakeTodoItemService>();

This	line	tells	ASP.NET	Core	to	use	the	 	FakeTodoItemService		whenever

the	 	ITodoItemService		interface	is	requested	in	a	constructor	(or

anywhere	else).

	AddSingleton		adds	your	service	to	the	service	container	as	a	singleton.

This	means	that	only	one	copy	of	the	 	FakeTodoItemService		is	created,

and	it's	reused	whenever	the	service	is	requested.	Later,	when	you	write

a	different	service	class	that	talks	to	a	database,	you'll	use	a	different

approach	(called	scoped)	instead.	I'll	explain	why	in	the	Use	a	database

chapter.

39

Use	dependency	injection

That's	it!	When	a	request	comes	in	and	is	routed	to	the	 	TodoController	,

ASP.NET	Core	will	look	at	the	available	services	and	automatically	supply

the	 	FakeTodoItemService		when	the	controller	asks	for	an

	ITodoItemService	.	Because	the	services	are	"injected"	from	the	service

container,	this	pattern	is	called	dependency	injection.

40

Finish	the	controller

Finish	the	controller

The	last	step	is	to	finish	the	controller	code.	The	controller	now	has	a	list

of	to-do	items	from	the	service	layer,	and	it	needs	to	put	those	items	into

a	 	TodoViewModel		and	bind	that	model	to	the	view	you	created	earlier:

Controllers/TodoController.cs

public	async	Task<IActionResult>	Index()

{

				var	items	=	await	_todoItemService.GetIncompleteItemsAsync();

				var	model	=	new	TodoViewModel()

				{

								Items	=	items

				};

				return	View(model);

}

If	you	haven't	already,	make	sure	these	 	using		statements	are	at	the	top

of	the	file:

using	AspNetCoreTodo.Services;

using	AspNetCoreTodo.Models;

If	you're	using	Visual	Studio	or	Visual	Studio	Code,	the	editor	will	suggest

these	 	using		statements	when	you	put	your	cursor	on	a	red	squiggly

line.

Test	it	out

41

Finish	the	controller

To	start	the	application,	press	F5	(if	you're	using	Visual	Studio	or	Visual

Studio	Code),	or	just	type	 	dotnet	run		in	the	terminal.	If	the	code

compiles	without	errors,	the	server	will	start	up	on	port	5000	by	default.

If	your	web	browser	didn't	open	automatically,	open	it	and	navigate	to

http://localhost:5000/todo.	You'll	see	the	view	you	created,	with	the

data	pulled	from	your	fake	database	(for	now).

Although	it's	possible	to	go	directly	to	 	http://localhost:5000/todo	,	it

would	be	nicer	to	add	an	item	called	My	to-dos	to	the	navbar.	To	do	this,

you	can	edit	the	shared	layout	file.

42

Update	the	layout

Update	the	layout

The	layout	file	at	 	Views/Shared/_Layout.cshtml		contains	the	"base"

HTML	for	each	view.	This	includes	the	navbar,	which	is	rendered	at	the

top	of	each	page.

To	add	a	new	item	to	the	navbar,	find	the	HTML	code	for	the	existing

navbar	items:

Views/Shared/_Layout.cshtml

<ul	class="nav	navbar-nav">

				<li><a	asp-area=""	asp-controller="Home"	asp-action="Index">

								Home

				</a></li>

				<li><a	asp-area=""	asp-controller="Home"	asp-action="About">

								About

				</a></li>

				<li><a	asp-area=""	asp-controller="Home"	asp-action="Contact">

								Contact

				</a></li>

</ul>

Add	your	own	item	that	points	to	the	 	Todo		controller	instead	of	 	Home	:

<li>

				<a	asp-controller="Todo"	asp-action="Index">My	to-dos</a>

</li>

The	 	asp-controller		and	 	asp-action		attributes	on	the	 	<a>		element

are	called	tag	helpers.	Before	the	view	is	rendered,	ASP.NET	Core

replaces	these	tag	helpers	with	real	HTML	attributes.	In	this	case,	a	URL

to	the	 	/Todo/Index		route	is	generated	and	added	to	the	 	<a>		element

43

Update	the	layout

as	an	 	href		attribute.	This	means	you	don't	have	to	hard-code	the	route

to	the	 	TodoController	.	Instead,	ASP.NET	Core	generates	it	for	you

automatically.

If	you've	used	Razor	in	ASP.NET	4.x,	you'll	notice	some	syntax

changes.	Instead	of	using	 	@Html.ActionLink()		to	generate	a	link

to	an	action,	tag	helpers	are	now	the	recommended	way	to	create

links	in	your	views.	Tag	helpers	are	useful	for	forms,	too	(you'll	see

why	in	a	later	chapter).	You	can	learn	about	other	tag	helpers	in

the	documentation	at	https://docs.asp.net.

44

Add	external	packages

Add	external	packages

One	of	the	big	advantages	of	using	a	mature	ecosystem	like	.NET	is	that

the	number	of	third-party	packages	and	plugins	is	huge.	Just	like	other

package	systems,	you	can	download	and	install	.NET	packages	that	help

with	almost	any	task	or	problem	you	can	imagine.

NuGet	is	both	the	package	manager	tool	and	the	official	package

repository	(at	https://www.nuget.org).	You	can	search	for	NuGet

packages	on	the	web,	and	install	them	from	your	local	machine	through

the	terminal	(or	the	GUI,	if	you're	using	Visual	Studio).

Install	the	Humanizer	package

At	the	end	of	the	last	chapter,	the	to-do	application	displayed	to-do

items	like	this:

The	due	date	column	is	displaying	dates	in	a	format	that's	good	for

machines	(called	ISO	8601),	but	clunky	for	humans.	Wouldn't	it	be	nicer

if	it	simply	read	"X	days	from	now"?

You	could	write	code	yourself	that	converted	an	ISO	8601	date	into	a

human-friendly	string,	but	fortunately,	there's	a	faster	way.

The	Humanizer	package	on	NuGet	solves	this	problem	by	providing

methods	that	can	"humanize"	or	rewrite	almost	anything:	dates,	times,

durations,	numbers,	and	so	on.	It's	a	fantastic	and	useful	open-source

45

Add	external	packages

project	that's	published	under	the	permissive	MIT	license.

To	add	it	to	your	project,	run	this	command	in	the	terminal:

dotnet	add	package	Humanizer

If	you	peek	at	the	 	AspNetCoreTodo.csproj		project	file,	you'll	see	a	new

	PackageReference		line	that	references	 	Humanizer	.

Use	Humanizer	in	the	view

To	use	a	package	in	your	code,	you	usually	need	to	add	a	 	using	

statement	that	imports	the	package	at	the	top	of	the	file.

Since	Humanizer	will	be	used	to	rewrite	dates	rendered	in	the	view,	you

can	use	it	directly	in	the	view	itself.	First,	add	a	 	@using		statement	at	the

top	of	the	view:

Views/Todo/Index.cshtml

@model	TodoViewModel

@using	Humanizer

//	...

Then,	update	the	line	that	writes	the	 	DueAt		property	to	use	Humanizer's

	Humanize		method:

<td>@item.DueAt.Humanize()</td>

Now	the	dates	are	much	more	readable:

46

Add	external	packages

There	are	packages	available	on	NuGet	for	everything	from	parsing	XML

to	machine	learning	to	posting	to	Twitter.	ASP.NET	Core	itself,	under	the

hood,	is	nothing	more	than	a	collection	of	NuGet	packages	that	are

added	to	your	project.

The	project	file	created	by	 	dotnet	new	mvc		includes	a	single

reference	to	the	 	Microsoft.AspNetCore.All		package,	which	is	a

convenient	"metapackage"	that	references	all	of	the	other

ASP.NET	Core	packages	you	need	for	a	typical	project.	That	way,

you	don't	need	to	have	hundreds	of	package	references	in	your

project	file.

In	the	next	chapter,	you'll	use	another	set	of	NuGet	packages	(a	system

called	Entity	Framework	Core)	to	write	code	that	interacts	with	a

database.

47

Use	a	database

Use	a	database

Writing	database	code	can	be	tricky.	Unless	you	really	know	what	you're

doing,	it's	a	bad	idea	to	paste	raw	SQL	query	strings	into	your	application

code.	An	object-relational	mapper	(ORM)	makes	it	easier	to	write	code

that	interacts	with	a	database	by	adding	a	layer	of	abstraction	between

your	code	and	the	database	itself.	Hibernate	in	Java	and	ActiveRecord	in

Ruby	are	two	well-known	ORMs.

There	are	a	number	of	ORMs	for	.NET,	including	one	built	by	Microsoft

and	included	in	ASP.NET	Core	by	default:	Entity	Framework	Core.	Entity

Framework	Core	makes	it	easy	to	connect	to	a	number	of	different

database	types,	and	lets	you	use	C#	code	to	create	database	queries	that

are	mapped	back	into	C#	models	(POCOs).

Remember	how	creating	a	service	interface	decoupled	the

controller	code	from	the	actual	service	class?	Entity	Framework

Core	is	like	a	big	interface	over	your	database.	Your	C#	code	can

stay	database-agnostic,	and	you	can	swap	out	different	providers

depending	on	the	underlying	database	technology.

Entity	Framework	Core	can	connect	to	relational	databases	like	SQL

Server,	PostgreSQL,	and	MySQL,	and	also	works	with	NoSQL	(document)

databases	like	Mongo.	During	development,	you'll	use	SQLite	in	this

project	to	make	things	easy	to	set	up.

48

Connect	to	a	database

Connect	to	a	database

There	are	a	few	things	you	need	to	use	Entity	Framework	Core	to

connect	to	a	database.	Since	you	used	 	dotnet	new		and	the	MVC	+

Individual	Auth	template	to	set	your	project,	you've	already	got	them:

The	Entity	Framework	Core	packages.	These	are	included	by	default

in	all	ASP.NET	Core	projects.

A	database	(naturally).	The	 	app.db		file	in	the	project	root	directory

is	a	small	SQLite	database	created	for	you	by	 	dotnet	new	.	SQLite	is

a	lightweight	database	engine	that	can	run	without	requiring	you	to

install	any	extra	tools	on	your	machine,	so	it's	easy	and	quick	to	use

in	development.

A	database	context	class.	The	database	context	is	a	C#	class	that

provides	an	entry	point	into	the	database.	It's	how	your	code	will

interact	with	the	database	to	read	and	save	items.	A	basic	context

class	already	exists	in	the	 	Data/ApplicationDbContext.cs		file.

A	connection	string.	Whether	you	are	connecting	to	a	local	file

database	(like	SQLite)	or	a	database	hosted	elsewhere,	you'll	define

a	string	that	contains	the	name	or	address	of	the	database	to

connect	to.	This	is	already	set	up	for	you	in	the	 	appsettings.json	

file:	the	connection	string	for	the	SQLite	database	is

	DataSource=app.db	.

Entity	Framework	Core	uses	the	database	context,	together	with	the

connection	string,	to	establish	a	connection	to	the	database.	You	need	to

tell	Entity	Framework	Core	which	context,	connection	string,	and

database	provider	to	use	in	the	 	ConfigureServices		method	of	the

	Startup		class.	Here's	what's	defined	for	you,	thanks	to	the	template:

services.AddDbContext<ApplicationDbContext>(options	=>

49

Connect	to	a	database

				options.UseSqlite(

								Configuration.GetConnectionString("DefaultConnection")));

This	code	adds	the	 	ApplicationDbContext		to	the	service	container,	and

tells	Entity	Framework	Core	to	use	the	SQLite	database	provider,	with

the	connection	string	from	configuration	( 	appsettings.json	).

As	you	can	see,	 	dotnet	new		creates	a	lot	of	stuff	for	you!	The	database

is	set	up	and	ready	to	be	used.	However,	it	doesn't	have	any	tables	for

storing	to-do	items.	In	order	to	store	your	 	TodoItem		entities,	you'll	need

to	update	the	context	and	migrate	the	database.

50

Update	the	context

Update	the	context

There's	not	a	whole	lot	going	on	in	the	database	context	yet:

Data/ApplicationDbContext.cs

public	class	ApplicationDbContext	

													:	IdentityDbContext<ApplicationUser>

{

				public	ApplicationDbContext(

								DbContextOptions<ApplicationDbContext>	options)

								:	base(options)

				{

				}

				protected	override	void	OnModelCreating(ModelBuilder	builder)

				{

								base.OnModelCreating(builder);

								//	...

				}

}

Add	a	 	DbSet		property	to	the	 	ApplicationDbContext	,	right	below	the

constructor:

public	ApplicationDbContext(

				DbContextOptions<ApplicationDbContext>	options)

				:	base(options)

{

}

public	DbSet<TodoItem>	Items	{	get;	set;	}

//	...

51

Update	the	context

A	 	DbSet		represents	a	table	or	collection	in	the	database.	By	creating	a

	DbSet<TodoItem>		property	called	 	Items	,	you're	telling	Entity

Framework	Core	that	you	want	to	store	 	TodoItem		entities	in	a	table

called	 	Items	.

You've	updated	the	context	class,	but	now	there's	one	small	problem:	the

context	and	database	are	now	out	of	sync,	because	there	isn't	actually	an

	Items		table	in	the	database.	(Just	updating	the	code	of	the	context	class

doesn't	change	the	database	itself.)

In	order	to	update	the	database	to	reflect	the	change	you	just	made	to

the	context,	you	need	to	create	a	migration.

If	you	already	have	an	existing	database,	search	the	web	for

"scaffold-dbcontext	existing	database"	and	read	Microsoft's

documentation	on	using	the	 	Scaffold-DbContext		tool	to	reverse-

engineer	your	database	structure	into	the	proper	 	DbContext		and

model	classes	automatically.

52

Create	a	migration

Create	a	migration

Migrations	keep	track	of	changes	to	the	database	structure	over	time.

They	make	it	possible	to	undo	(roll	back)	a	set	of	changes,	or	create	a

second	database	with	the	same	structure	as	the	first.	With	migrations,

you	have	a	full	history	of	modifications	like	adding	or	removing	columns

(and	entire	tables).

In	the	previous	chapter,	you	added	an	 	Items		set	to	the	context.	Since

the	context	now	includes	a	set	(or	table)	that	doesn't	exist	in	the

database,	you	need	to	create	a	migration	to	update	the	database:

dotnet	ef	migrations	add	AddItems

This	creates	a	new	migration	called	 	AddItems		by	examining	any	changes

you've	made	to	the	context.

If	you	get	an	error	like	 	No	executable	found	matching	command

"dotnet-ef"	,	make	sure	you're	in	the	right	directory.	These

commands	must	be	run	from	the	project	root	directory	(where	the

	Program.cs		file	is).

If	you	open	up	the	 	Data/Migrations		directory,	you'll	see	a	few	files:

53

Create	a	migration

The	first	migration	file	(with	a	name	like	 	00_CreateIdentitySchema.cs	)

was	created	and	applied	for	you	way	back	when	you	ran	 	dotnet	new	.

Your	new	 	AddItem		migration	is	prefixed	with	a	timestamp	when	you

create	it.

You	can	see	a	list	of	migrations	with	 	dotnet	ef	migrations	list	.

If	you	open	your	migration	file,	you'll	see	two	methods	called	 	Up		and

	Down	:

Data/Migrations/_AddItems.cs

protected	override	void	Up(MigrationBuilder	migrationBuilder)

{

				//	(...	some	code)

				migrationBuilder.CreateTable(

								name:	"Items",

								columns:	table	=>	new

								{

												Id	=	table.Column<Guid>(nullable:	false),

												DueAt	=	table.Column<DateTimeOffset>(nullable:	true),

												IsDone	=	table.Column<bool>(nullable:	false),

												Title	=	table.Column<string>(nullable:	true)

								},

								constraints:	table	=>

								{

												table.PrimaryKey("PK_Items",	x	=>	x.Id);

								});

				//	(some	code...)

}

protected	override	void	Down(MigrationBuilder	migrationBuilder)

{

				//	(...	some	code)

				migrationBuilder.DropTable(

								name:	"Items");

				//	(some	code...)

}

54

Create	a	migration

The	 	Up		method	runs	when	you	apply	the	migration	to	the	database.

Since	you	added	a	 	DbSet<TodoItem>		to	the	database	context,	Entity

Framework	Core	will	create	an	 	Items		table	(with	columns	that	match	a

	TodoItem	)	when	you	apply	the	migration.

The	 	Down		method	does	the	opposite:	if	you	need	to	undo	(roll	back)	the

migration,	the	 	Items		table	will	be	dropped.

Workaround	for	SQLite	limitations

There	are	some	limitations	of	SQLite	that	get	in	the	way	if	you	try	to	run

the	migration	as-is.	Until	this	problem	is	fixed,	use	this	workaround:

Comment	out	or	remove	the	 	migrationBuilder.AddForeignKey		lines

in	the	 	Up		method.

Comment	out	or	remove	any	 	migrationBuilder.DropForeignKey		lines

in	the	 	Down		method.

If	you	use	a	full-fledged	SQL	database,	like	SQL	Server	or	MySQL,	this

won't	be	an	issue	and	you	won't	need	to	do	this	(admittedly	hackish)

workaround.

Apply	the	migration

The	final	step	after	creating	one	(or	more)	migrations	is	to	actually	apply

them	to	the	database:

dotnet	ef	database	update

This	command	will	cause	Entity	Framework	Core	to	create	the	 	Items	

table	in	the	database.

55

Create	a	migration

If	you	want	to	roll	back	the	database,	you	can	provide	the	name	of

the	previous	migration:	 	dotnet	ef	database	update

CreateIdentitySchema		This	will	run	the	 	Down		methods	of	any

migrations	newer	than	the	migration	you	specify.

If	you	need	to	completely	erase	the	database	and	start	over,	run

	dotnet	ef	database	drop		followed	by	 	dotnet	ef	database	update	

to	re-scaffold	the	database	and	bring	it	up	to	the	current

migration.

That's	it!	Both	the	database	and	the	context	are	ready	to	go.	Next,	you'll

use	the	context	in	your	service	layer.

56

Create	a	new	service	class

Create	a	new	service	class

Back	in	the	MVC	basics	chapter,	you	created	a	 	FakeTodoItemService		that

contained	hard-coded	to-do	items.	Now	that	you	have	a	database

context,	you	can	create	a	new	service	class	that	will	use	Entity

Framework	Core	to	get	the	real	items	from	the	database.

Delete	the	 	FakeTodoItemService.cs		file,	and	create	a	new	file:

Services/TodoItemService.cs

using	System;

using	System.Collections.Generic;

using	System.Linq;

using	System.Threading.Tasks;

using	AspNetCoreTodo.Data;

using	AspNetCoreTodo.Models;

using	Microsoft.EntityFrameworkCore;

namespace	AspNetCoreTodo.Services

{

				public	class	TodoItemService	:	ITodoItemService

				{

								private	readonly	ApplicationDbContext	_context;

								public	TodoItemService(ApplicationDbContext	context)

								{

												_context	=	context;

								}

								public	async	Task<TodoItem[]>	GetIncompleteItemsAsync()

								{

												return	await	_context.Items

																.Where(x	=>	x.IsDone	==	false)

																.ToArrayAsync();

								}

				}

}

57

Create	a	new	service	class

You'll	notice	the	same	dependency	injection	pattern	here	that	you	saw	in

the	MVC	basics	chapter,	except	this	time	it's	the	 	ApplicationDbContext	

that's	getting	injected.	The	 	ApplicationDbContext		is	already	being	added

to	the	service	container	in	the	 	ConfigureServices		method,	so	it's

available	for	injection	here.

Let's	take	a	closer	look	at	the	code	of	the	 	GetIncompleteItemsAsync	

method.	First,	it	uses	the	 	Items		property	of	the	context	to	access	all	the

to-do	items	in	the	 	DbSet	:

var	items	=	await	_context.Items

Then,	the	 	Where		method	is	used	to	filter	only	the	items	that	are	not

complete:

.Where(x	=>	x.IsDone	==	false)

The	 	Where		method	is	a	feature	of	C#	called	LINQ	(language	integrated

query),	which	takes	inspiration	from	functional	programming	and	makes

it	easy	to	express	database	queries	in	code.	Under	the	hood,	Entity

Framework	Core	translates	the	 	Where		method	into	a	statement	like

	SELECT	*	FROM	Items	WHERE	IsDone	=	0	,	or	an	equivalent	query	document

in	a	NoSQL	database.

Finally,	the	 	ToArrayAsync		method	tells	Entity	Framework	Core	to	get	all

the	entities	that	matched	the	filter	and	return	them	as	an	array.	The

	ToArrayAsync		method	is	asynchronous	(it	returns	a	 	Task	),	so	it	must	be

	await	ed	to	get	its	value.

To	make	the	method	a	little	shorter,	you	can	remove	the	intermediate

	items		variable	and	just	return	the	result	of	the	query	directly	(which

does	the	same	thing):

public	async	Task<TodoItem[]>	GetIncompleteItemsAsync()

58

Create	a	new	service	class

{

				return	await	_context.Items

								.Where(x	=>	x.IsDone	==	false)

								.ToArrayAsync();

}

Update	the	service	container

Because	you	deleted	the	 	FakeTodoItemService		class,	you'll	need	to

update	the	line	in	 	ConfigureServices		that	is	wiring	up	the

	ITodoItemService		interface:

services.AddScoped<ITodoItemService,	TodoItemService>();

	AddScoped		adds	your	service	to	the	service	container	using	the	scoped

lifecycle.	This	means	that	a	new	instance	of	the	 	TodoItemService		class

will	be	created	during	each	web	request.	This	is	required	for	service

classes	that	interact	with	a	database.

Adding	a	service	class	that	interacts	with	Entity	Framework	Core

(and	your	database)	with	the	singleton	lifecycle	(or	other	lifecycles)

can	cause	problems,	because	of	how	Entity	Framework	Core

manages	database	connections	per	request	under	the	hood.	To

avoid	that,	always	use	the	scoped	lifecycle	for	services	that

interact	with	Entity	Framework	Core.

The	 	TodoController		that	depends	on	an	injected	 	ITodoItemService		will

be	blissfully	unaware	of	the	change	in	services	classes,	but	under	the

hood	it'll	be	using	Entity	Framework	Core	and	talking	to	a	real	database!

Test	it	out

Start	up	the	application	and	navigate	to	 	http://localhost:5000/todo	.

The	fake	items	are	gone,	and	your	application	is	making	real	queries	to

the	database.	There	doesn't	happen	to	be	any	saved	to-do	items,	so	it's

59

Create	a	new	service	class

blank	for	now.

In	the	next	chapter,	you'll	add	more	features	to	the	application,	starting

with	the	ability	to	create	new	to-do	items.

60

Add	more	features

Add	more	features

Now	that	you've	connected	to	a	database	using	Entity	Framework	Core,

you're	ready	to	add	some	more	features	to	the	application.	First,	you'll

make	it	possible	to	add	new	to-do	items	using	a	form.

61

Add	new	to-do	items

Add	new	to-do	items

The	user	will	add	new	to-do	items	with	a	simple	form	below	the	list:

Adding	this	feature	requires	a	few	steps:

Adding	a	form	to	the	view

Creating	a	new	action	on	the	controller	to	handle	the	form

Adding	code	to	the	service	layer	to	update	the	database

Add	a	form

The	 	Views/Todo/Index.cshtml		view	has	a	placeholder	for	the	Add	Item

form:

<div	class="panel-footer	add-item-form">

		<!--	TODO:	Add	item	form	-->

</div>

To	keep	things	separate	and	organized,	you'll	create	the	form	as	a	partial

view.	A	partial	view	is	a	small	piece	of	a	larger	view	that	lives	in	a

separate	file.

Create	an	 	AddItemPartial.cshtml		view:

Views/Todo/AddItemPartial.cshtml

62

Add	new	to-do	items

@model	TodoItem

<form	asp-action="AddItem"	method="POST">

				<label	asp-for="Title">Add	a	new	item:</label>

				<input	asp-for="Title">

				<button	type="submit">Add</button>

</form>

The	 	asp-action		tag	helper	can	generate	a	URL	for	the	form,	just	like

when	you	use	it	on	an	 	<a>		element.	In	this	case,	the	 	asp-action		helper

gets	replaced	with	the	real	path	to	the	 	AddItem		route	you'll	create:

<form	action="/Todo/AddItem"	method="POST">

Adding	an	 	asp-		tag	helper	to	the	 	<form>		element	also	adds	a	hidden

field	to	the	form	containing	a	verification	token.	This	verification	token

can	be	used	to	prevent	cross-site	request	forgery	(CSRF)	attacks.	You'll

verify	the	token	when	you	write	the	action.

That	takes	care	of	creating	the	partial	view.	Now,	reference	it	from	the

main	Todo	view:

Views/Todo/Index.cshtml

<div	class="panel-footer	add-item-form">

		@await	Html.PartialAsync("AddItemPartial",	new	TodoItem())

</div>

Add	an	action

When	a	user	clicks	Add	on	the	form	you	just	created,	their	browser	will

construct	a	POST	request	to	 	/Todo/AddItem		on	your	application.	That

won't	work	right	now,	because	there	isn't	any	action	that	can	handle	the

	/Todo/AddItem		route.	If	you	try	it	now,	ASP.NET	Core	will	return	a	 	404

Not	Found		error.

63

Add	new	to-do	items

You'll	need	to	create	a	new	action	called	 	AddItem		on	the

	TodoController	:

[ValidateAntiForgeryToken]

public	async	Task<IActionResult>	AddItem(TodoItem	newItem)

{

				if	(!ModelState.IsValid)

				{

								return	RedirectToAction("Index");

				}

				var	successful	=	await	_todoItemService.AddItemAsync(newItem);

				if	(!successful)

				{

								return	BadRequest("Could	not	add	item.");

				}

				return	RedirectToAction("Index");

}

Notice	how	the	new	 	AddItem		action	accepts	a	 	TodoItem		parameter?

This	is	the	same	 	TodoItem		model	you	created	in	the	MVC	basics	chapter

to	store	information	about	a	to-do	item.	When	it's	used	here	as	an	action

parameter,	ASP.NET	Core	will	automatically	perform	a	process	called

model	binding.

Model	binding	looks	at	the	data	in	a	request	and	tries	to	intelligently

match	the	incoming	fields	with	properties	on	the	model.	In	other	words,

when	the	user	submits	this	form	and	their	browser	POSTs	to	this	action,

ASP.NET	Core	will	grab	the	information	from	the	form	and	place	it	in	the

	newItem		variable.

The	 	[ValidateAntiForgeryToken]		attribute	before	the	action	tells

ASP.NET	Core	that	it	should	look	for	(and	verify)	the	hidden	verification

token	that	was	added	to	the	form	by	the	 	asp-action		tag	helper.	This	is

an	important	security	measure	to	prevent	cross-site	request	forgery

64

Add	new	to-do	items

(CSRF)	attacks,	where	your	users	could	be	tricked	into	submitting	data

from	a	malicious	site.	The	verification	token	ensures	that	your	application

is	actually	the	one	that	rendered	and	submitted	the	form.

Take	a	look	at	the	 	AddItemPartial.cshtml		view	once	more.	The	 	@model

TodoItem		line	at	the	top	of	the	file	tells	ASP.NET	Core	that	the	view

should	expect	to	be	paired	with	the	 	TodoItem		model.	This	makes	it

possible	to	use	 	asp-for="Title"		on	the	 	<input>		tag	to	let	ASP.NET

Core	know	that	this	input	element	is	for	the	 	Title		property.

Because	of	the	 	@model		line,	the	partial	view	will	expect	to	be	passed	a

	TodoItem		object	when	it's	rendered.	Passing	it	a	 	new	TodoItem		via

	Html.PartialAsync		initializes	the	form	with	an	empty	item.	(Try

appending	 	{	Title	=	"hello"	}		and	see	what	happens!)

During	model	binding,	any	model	properties	that	can't	be	matched	up

with	fields	in	the	request	are	ignored.	Since	the	form	only	includes	a

	Title		input	element,	you	can	expect	that	the	other	properties	on

	TodoItem		(the	 	IsDone		flag,	the	 	DueAt		date)	will	be	empty	or	contain

default	values.

Instead	of	reusing	the	 	TodoItem		model,	another	approach	would

be	to	create	a	separate	model	(like	 	NewTodoItem	)	that's	only	used

for	this	action	and	only	has	the	specific	properties	(Title)	you	need

for	adding	a	new	to-do	item.	Model	binding	is	still	used,	but	this

way	you've	separated	the	model	that's	used	for	storing	a	to-do

item	in	the	database	from	the	model	that's	used	for	binding

incoming	request	data.	This	is	sometimes	called	a	binding	model	or

a	data	transfer	object	(DTO).	This	pattern	is	common	in	larger,

more	complex	projects.

After	binding	the	request	data	to	the	model,	ASP.NET	Core	also

performs	model	validation.	Validation	checks	whether	the	data	bound	to

the	model	from	the	incoming	request	makes	sense	or	is	valid.	You	can

65

Add	new	to-do	items

add	attributes	to	the	model	to	tell	ASP.NET	Core	how	it	should	be

validated.

The	 	[Required]		attribute	on	the	 	Title		property	tells	ASP.NET	Core's

model	validator	to	consider	the	title	invalid	if	it	is	missing	or	blank.	Take	a

look	at	the	code	of	the	 	AddItem		action:	the	first	block	checks	whether

the	 	ModelState		(the	model	validation	result)	is	valid.	It's	customary	to	do

this	validation	check	right	at	the	beginning	of	the	action:

if	(!ModelState.IsValid)

{

				return	RedirectToAction("Index");

}

If	the	 	ModelState		is	invalid	for	any	reason,	the	browser	will	be

redirected	to	the	 	/Todo/Index		route,	which	refreshes	the	page.

Next,	the	controller	calls	into	the	service	layer	to	do	the	actual	database

operation	of	saving	the	new	to-do	item:

var	successful	=	await	_todoItemService.AddItemAsync(newItem);

if	(!successful)

{

				return	BadRequest(new	{	error	=	"Could	not	add	item."	});

}

The	 	AddItemAsync		method	will	return	 	true		or	 	false		depending	on

whether	the	item	was	successfully	added	to	the	database.	If	it	fails	for

some	reason,	the	action	will	return	an	HTTP	 	400	Bad	Request		error

along	with	an	object	that	contains	an	error	message.

Finally,	if	everything	completed	without	errors,	the	action	redirects	the

browser	to	the	 	/Todo/Index		route,	which	refreshes	the	page	and

displays	the	new,	updated	list	of	to-do	items	to	the	user.

Add	a	service	method

66

Add	new	to-do	items

If	you're	using	a	code	editor	that	understands	C#,	you'll	see	red	squiggely

lines	under	 	AddItemAsync		because	the	method	doesn't	exist	yet.

As	a	last	step,	you	need	to	add	a	method	to	the	service	layer.	First,	add	it

to	the	interface	definition	in	 	ITodoItemService	:

public	interface	ITodoItemService

{

				Task<TodoItem[]>	GetIncompleteItemsAsync();

				Task<bool>	AddItemAsync(TodoItem	newItem);

}

Then,	the	actual	implementation	in	 	TodoItemService	:

public	async	Task<bool>	AddItemAsync(TodoItem	newItem)

{

				newItem.Id	=	Guid.NewGuid();

				newItem.IsDone	=	false;

				newItem.DueAt	=	DateTimeOffset.Now.AddDays(3);

				_context.Items.Add(newItem);

				var	saveResult	=	await	_context.SaveChangesAsync();

				return	saveResult	==	1;

}

The	 	newItem.Title		property	has	already	been	set	by	ASP.NET	Core's

model	binder,	so	this	method	only	needs	to	assign	an	ID	and	set	the

default	values	for	the	other	properties.	Then,	the	new	item	is	added	to

the	database	context.	It	isn't	actually	saved	until	you	call

	SaveChangesAsync()	.	If	the	save	operation	was	successful,

	SaveChangesAsync()		will	return	1.

Try	it	out

67

Add	new	to-do	items

Run	the	application	and	add	some	items	to	your	to-do	list	with	the	form.

Since	the	items	are	being	stored	in	the	database,	they'll	still	be	there

even	after	you	stop	and	start	the	application	again.

As	an	extra	challenge,	try	adding	a	date	picker	using	HTML	and

JavaScript,	and	let	the	user	choose	an	(optional)	date	for	the

	DueAt		property.	Then,	use	that	date	instead	of	always	making

new	tasks	that	are	due	in	3	days.

68

Complete	items	with	a	checkbox

Complete	items	with	a	checkbox

Adding	items	to	your	to-do	list	is	great,	but	eventually	you'll	need	to	get

things	done,	too.	In	the	 	Views/Todo/Index.cshtml		view,	a	checkbox	is

rendered	for	each	to-do	item:

<input	type="checkbox"	class="done-checkbox">

Clicking	the	checkbox	doesn't	do	anything	(yet).	Just	like	the	last	chapter,

you'll	add	this	behavior	using	forms	and	actions.	In	this	case,	you'll	also

need	a	tiny	bit	of	JavaScript	code.

Add	form	elements	to	the	view

First,	update	the	view	and	wrap	each	checkbox	with	a	 	<form>		element.

Then,	add	a	hidden	element	containing	the	item's	ID:

Views/Todo/Index.cshtml

<td>

				<form	asp-action="MarkDone"	method="POST">

								<input	type="checkbox"	class="done-checkbox">

								<input	type="hidden"	name="id"	value="@item.Id">

				</form>

</td>

When	the	 	foreach		loop	runs	in	the	view	and	prints	a	row	for	each	to-do

item,	a	copy	of	this	form	will	exist	in	each	row.	The	hidden	input

containing	the	to-do	item's	ID	makes	it	possible	for	your	controller	code

to	tell	which	box	was	checked.	(Without	it,	you'd	be	able	to	tell	that	some

box	was	checked,	but	not	which	one.)

69

Complete	items	with	a	checkbox

If	you	run	your	application	right	now,	the	checkboxes	still	won't	do

anything,	because	there's	no	submit	button	to	tell	the	browser	to	create

a	POST	request	with	the	form's	data.	You	could	add	a	submit	button

under	each	checkbox,	but	that	would	be	a	silly	user	experience.	Ideally,

clicking	the	checkbox	should	automatically	submit	the	form.	You	can

achieve	that	by	adding	some	JavaScript.

Add	JavaScript	code

Find	the	 	site.js		file	in	the	 	wwwroot/js		directory	and	add	this	code:

wwwroot/js/site.js

$(document).ready(function()	{

				//	Wire	up	all	of	the	checkboxes	to	run	markCompleted()

				$('.done-checkbox').on('click',	function(e)	{

								markCompleted(e.target);

				});

});

function	markCompleted(checkbox)	{

				checkbox.disabled	=	true;

				var	row	=	checkbox.closest('tr');

				$(row).addClass('done');

				var	form	=	checkbox.closest('form');

				form.submit();

}

This	code	first	uses	jQuery	(a	JavaScript	helper	library)	to	attach	some

code	to	the	 	click		even	of	all	the	checkboxes	on	the	page	with	the	CSS

class	 	done-checkbox	.	When	a	checkbox	is	clicked,	the	 	markCompleted()	

function	is	run.

The	 	markCompleted()		function	does	a	few	things:

70

Complete	items	with	a	checkbox

Adds	the	 	disabled		attribute	to	the	checkbox	so	it	can't	be	clicked

again

Adds	the	 	done		CSS	class	to	the	parent	row	that	contains	the

checkbox,	which	changes	the	way	the	row	looks	based	on	the	CSS

rules	in	 	style.css	

Submits	the	form

That	takes	care	of	the	view	and	frontend	code.	Now	it's	time	to	add	a

new	action!

Add	an	action	to	the	controller

As	you've	probably	guessed,	you	need	to	add	an	action	called	 	MarkDone	

in	the	 	TodoController	:

[ValidateAntiForgeryToken]

public	async	Task<IActionResult>	MarkDone(Guid	id)

{

				if	(id	==	Guid.Empty)

				{

								return	RedirectToAction("Index");

				}

				var	successful	=	await	_todoItemService.MarkDoneAsync(id);

				if	(!successful)

				{

								return	BadRequest("Could	not	mark	item	as	done.");

				}

				return	RedirectToAction("Index");

}

Let's	step	through	each	line	of	this	action	method.	First,	the	method

accepts	a	 	Guid		parameter	called	 	id		in	the	method	signature.	Unlike

the	 	AddItem		action,	which	used	a	model	and	model	binding/validation,

the	 	id		parameter	is	very	simple.	If	the	incoming	request	data	includes	a

71

Complete	items	with	a	checkbox

field	called	 	id	,	ASP.NET	Core	will	try	to	parse	it	as	a	guid.	This	works

because	the	hidden	element	you	added	to	the	checkbox	form	is	named

	id	.

Since	you	aren't	using	model	binding,	there's	no	 	ModelState		to	check	for

validity.	Instead,	you	can	check	the	guid	value	directly	to	make	sure	it's

valid.	If	for	some	reason	the	 	id		parameter	in	the	request	was	missing	or

couldn't	be	parsed	as	a	guid,	 	id		will	have	a	value	of	 	Guid.Empty	.	If

that's	the	case,	the	action	tells	the	browser	to	redirect	to	 	/Todo/Index	

and	refresh	the	page.

Next,	the	controller	needs	to	call	the	service	layer	to	update	the

database.	This	will	be	handled	by	a	new	method	called	 	MarkDoneAsync	

on	the	 	ITodoItemService		interface,	which	will	return	true	or	false

depending	on	whether	the	update	succeeded:

var	successful	=	await	_todoItemService.MarkDoneAsync(id);

if	(!successful)

{

				return	BadRequest("Could	not	mark	item	as	done.");

}

Finally,	if	everything	looks	good,	the	browser	is	redirected	to	the

	/Todo/Index		action	and	the	page	is	refreshed.

With	the	view	and	controller	updated,	all	that's	left	is	adding	the	missing

service	method.

Add	a	service	method

First,	add	 	MarkDoneAsync		to	the	interface	definition:

Services/ITodoItemService.cs

Task<bool>	MarkDoneAsync(Guid	id);

72

Complete	items	with	a	checkbox

Then,	add	the	concrete	implementation	to	the	 	TodoItemService	:

Services/TodoItemService.cs

public	async	Task<bool>	MarkDoneAsync(Guid	id)

{

				var	item	=	await	_context.Items

								.Where(x	=>	x.Id	==	id)

								.SingleOrDefaultAsync();

				if	(item	==	null)	return	false;

				item.IsDone	=	true;

				var	saveResult	=	await	_context.SaveChangesAsync();

				return	saveResult	==	1;	//	One	entity	should	have	been	updated

}

This	method	uses	Entity	Framework	Core	and	 	Where()		to	find	an	item

by	ID	in	the	database.	The	 	SingleOrDefaultAsync()		method	will	either

return	the	item	or	 	null		if	it	couldn't	be	found.

Once	you're	sure	that	 	item		isn't	null,	it's	a	simple	matter	of	setting	the

	IsDone		property:

item.IsDone	=	true;

Changing	the	property	only	affects	the	local	copy	of	the	item	until

	SaveChangesAsync()		is	called	to	persist	the	change	back	to	the	database.

	SaveChangesAsync()		returns	a	number	that	indicates	how	many	entities

were	updated	during	the	save	operation.	In	this	case,	it'll	either	be	1	(the

item	was	updated)	or	0	(something	went	wrong).

Try	it	out

73

Complete	items	with	a	checkbox

Run	the	application	and	try	checking	some	items	off	the	list.	Refresh	the

page	and	they'll	disappear	completely,	because	of	the	 	Where()		filter	in

the	 	GetIncompleteItemsAsync()		method.

Right	now,	the	application	contains	a	single,	shared	to-do	list.	It'd	be

even	more	useful	if	it	kept	track	of	individual	to-do	lists	for	each	user.	In

the	next	chapter,	you'll	add	login	and	security	features	to	the	project.

74

Security	and	identity

Security	and	identity

Security	is	a	major	concern	of	any	modern	web	application	or	API.	It's

important	to	keep	your	user	or	customer	data	safe	and	out	of	the	hands

of	attackers.	This	is	a	very	broad	topic,	involving	things	like:

Sanitizing	data	input	to	prevent	SQL	injection	attacks

Preventing	cross-domain	(CSRF)	attacks	in	forms

Using	HTTPS	(connection	encryption)	so	data	can't	be	intercepted	as

it	travels	over	the	Internet

Giving	users	a	way	to	securely	sign	in	with	a	password	or	other

credentials

Designing	password	reset,	account	recovery,	and	multi-factor

authentication	flows

ASP.NET	Core	can	help	make	all	of	this	easier	to	implement.	The	first

two	(protection	against	SQL	injection	and	cross-domain	attacks)	are

already	built-in,	and	you	can	add	a	few	lines	of	code	to	enable	HTTPS

support.	This	chapter	will	mainly	focus	on	the	identity	aspects	of

security:	handling	user	accounts,	authenticating	(logging	in)	your	users

securely,	and	making	authorization	decisions	once	they	are

authenticated.

Authentication	and	authorization	are	distinct	ideas	that	are	often

confused.	Authentication	deals	with	whether	a	user	is	logged	in,

while	authorization	deals	with	what	they	are	allowed	to	do	after

they	log	in.	You	can	think	of	authentication	as	asking	the	question,

"Do	I	know	who	this	user	is?"	While	authorization	asks,	"Does	this

user	have	permission	to	do	X?"

75

Security	and	identity

The	MVC	+	Individual	Authentication	template	you	used	to	scaffold	the

project	includes	a	number	of	classes	built	on	top	of	ASP.NET	Core

Identity,	an	authentication	and	identity	system	that's	part	of	ASP.NET

Core.	Out	of	the	box,	this	adds	the	ability	to	log	in	with	an	email	and

password.

What	is	ASP.NET	Core	Identity?

ASP.NET	Core	Identity	is	the	identity	system	that	ships	with	ASP.NET

Core.	Like	everything	else	in	the	ASP.NET	Core	ecosystem,	it's	a	set	of

NuGet	packages	that	can	be	installed	in	any	project	(and	are	already

included	if	you	use	the	default	template).

ASP.NET	Core	Identity	takes	care	of	storing	user	accounts,	hashing	and

storing	passwords,	and	managing	roles	for	users.	It	supports

email/password	login,	multi-factor	authentication,	social	login	with

providers	like	Google	and	Facebook,	as	well	as	connecting	to	other

services	using	protocols	like	OAuth	2.0	and	OpenID	Connect.

The	Register	and	Login	views	that	ship	with	the	MVC	+	Individual

Authentication	template	already	take	advantage	of	ASP.NET	Core

Identity,	and	they	already	work!	Try	registering	for	an	account	and

logging	in.

76

Require	authentication

Require	authentication

Often	you'll	want	to	require	the	user	to	log	in	before	they	can	access

certain	parts	of	your	application.	For	example,	it	makes	sense	to	show

the	home	page	to	everyone	(whether	you're	logged	in	or	not),	but	only

show	your	to-do	list	after	you've	logged	in.

You	can	use	the	 	[Authorize]		attribute	in	ASP.NET	Core	to	require	a

logged-in	user	for	a	particular	action,	or	an	entire	controller.	To	require

authentication	for	all	actions	of	the	 	TodoController	,	add	the	attribute

above	the	first	line	of	the	controller:

Controllers/TodoController.cs

[Authorize]

public	class	TodoController	:	Controller

{

				//	...

}

Add	this	 	using		statement	at	the	top	of	the	file:

using	Microsoft.AspNetCore.Authorization;

Try	running	the	application	and	accessing	 	/todo		without	being	logged

in.	You'll	be	redirected	to	the	login	page	automatically.

The	 	[Authorize]		attribute	is	actually	doing	an	authentication

check	here,	not	an	authorization	check	(despite	the	name	of	the

attribute).	Later,	you'll	use	the	attribute	to	check	both

authentication	and	authorization.

77

Require	authentication

78

Using	identity	in	the	application

Using	identity	in	the	application

The	to-do	list	items	themselves	are	still	shared	between	all	users,

because	the	stored	to-do	entities	aren't	tied	to	a	particular	user.	Now

that	the	 	[Authorize]		attribute	ensures	that	you	must	be	logged	in	to

see	the	to-do	view,	you	can	filter	the	database	query	based	on	who	is

logged	in.

First,	inject	a	 	UserManager<ApplicationUser>		into	the	 	TodoController	:

Controllers/TodoController.cs

[Authorize]

public	class	TodoController	:	Controller

{

				private	readonly	ITodoItemService	_todoItemService;

				private	readonly	UserManager<ApplicationUser>	_userManager;

				public	TodoController(ITodoItemService	todoItemService,

								UserManager<ApplicationUser>	userManager)

				{

								_todoItemService	=	todoItemService;

								_userManager	=	userManager;

				}

				//	...

}

You'll	need	to	add	a	new	 	using		statement	at	the	top:

using	Microsoft.AspNetCore.Identity;

The	 	UserManager		class	is	part	of	ASP.NET	Core	Identity.	You	can	use	it

to	get	the	current	user	in	the	 	Index		action:

public	async	Task<IActionResult>	Index()

79

Using	identity	in	the	application

{

				var	currentUser	=	await	_userManager.GetUserAsync(User);

				if	(currentUser	==	null)	return	Challenge();

				var	items	=	await	_todoItemService

								.GetIncompleteItemsAsync(currentUser);

				var	model	=	new	TodoViewModel()

				{

								Items	=	items

				};

				return	View(model);

}

The	new	code	at	the	top	of	the	action	method	uses	the	 	UserManager		to

look	up	the	current	user	from	the	 	User		property	available	in	the	action:

var	currentUser	=	await	_userManager.GetUserAsync(User);

If	there	is	a	logged-in	user,	the	 	User		property	contains	a	lightweight

object	with	some	(but	not	all)	of	the	user's	information.	The	 	UserManager	

uses	this	to	look	up	the	full	user	details	in	the	database	via	the

	GetUserAsync()		method.

The	value	of	 	currentUser		should	never	be	null,	because	the

	[Authorize]		attribute	is	present	on	the	controller.	However,	it's	a	good

idea	to	do	a	sanity	check,	just	in	case.	You	can	use	the	 	Challenge()	

method	to	force	the	user	to	log	in	again	if	their	information	is	missing:

if	(currentUser	==	null)	return	Challenge();

Since	you're	now	passing	an	 	ApplicationUser		parameter	to

	GetIncompleteItemsAsync()	,	you'll	need	to	update	the	 	ITodoItemService	

interface:

Services/ITodoItemService.cs

80

Using	identity	in	the	application

public	interface	ITodoItemService

{

				Task<TodoItem[]>	GetIncompleteItemsAsync(

								ApplicationUser	user);

				//	...

}

Since	you	changed	the	 	ITodoItemService		interface,	you	also	need	to

update	the	signature	of	the	 	GetIncompleteItemsAsync()		method	in	the

	TodoItemService	:

Services/TodoItemService

public	async	Task<TodoItem[]>	GetIncompleteItemsAsync(

				ApplicationUser	user)

The	next	step	is	to	update	the	database	query	and	add	a	filter	to	show

only	the	items	created	by	the	current	user.	Before	you	can	do	that,	you

need	to	add	a	new	property	to	the	database.

Update	the	database

You'll	need	to	add	a	new	property	to	the	 	TodoItem		entity	model	so	each

item	can	"remember"	the	user	that	owns	it:

Models/TodoItem.cs

public	string	UserId	{	get;	set;	}

Since	you	updated	the	entity	model	used	by	the	database	context,	you

also	need	to	migrate	the	database.	Create	a	new	migration	using	 	dotnet

ef		in	the	terminal:

dotnet	ef	migrations	add	AddItemUserId

81

Using	identity	in	the	application

This	creates	a	new	migration	called	 	AddItemUserId		which	will	add	a	new

column	to	the	 	Items		table,	mirroring	the	change	you	made	to	the

	TodoItem		model.

Use	 	dotnet	ef		again	to	apply	it	to	the	database:

dotnet	ef	database	update

Update	the	service	class

With	the	database	and	the	database	context	updated,	you	can	now

update	the	 	GetIncompleteItemsAsync()		method	in	the	 	TodoItemService	

and	add	another	clause	to	the	 	Where		statement:

Services/TodoItemService.cs

public	async	Task<TodoItem[]>	GetIncompleteItemsAsync(

				ApplicationUser	user)

{

				return	await	_context.Items

								.Where(x	=>	x.IsDone	==	false	&&	x.UserId	==	user.Id)

								.ToArrayAsync();

}

If	you	run	the	application	and	register	or	log	in,	you'll	see	an	empty	to-do

list	once	again.	Unfortunately,	any	items	you	try	to	add	disappear	into

the	ether,	because	you	haven't	updated	the	 	AddItem		action	to	be	user-

aware	yet.

Update	the	AddItem	and	MarkDone	actions

You'll	need	to	use	the	 	UserManager		to	get	the	current	user	in	the

	AddItem		and	 	MarkDone		action	methods,	just	like	you	did	in	 	Index	.

Here	are	both	updated	methods:

82

Using	identity	in	the	application

Controllers/TodoController.cs

[ValidateAntiForgeryToken]

public	async	Task<IActionResult>	AddItem(TodoItem	newItem)

{

				if	(!ModelState.IsValid)

				{

								return	RedirectToAction("Index");

				}

				var	currentUser	=	await	_userManager.GetUserAsync(User);

				if	(currentUser	==	null)	return	Challenge();

				var	successful	=	await	_todoItemService

								.AddItemAsync(newItem,	currentUser);

				if	(!successful)

				{

								return	BadRequest("Could	not	add	item.");

				}

				return	RedirectToAction("Index");

}

[ValidateAntiForgeryToken]

public	async	Task<IActionResult>	MarkDone(Guid	id)

{

				if	(id	==	Guid.Empty)

				{

								return	RedirectToAction("Index");

				}

				var	currentUser	=	await	_userManager.GetUserAsync(User);

				if	(currentUser	==	null)	return	Challenge();

				var	successful	=	await	_todoItemService

								.MarkDoneAsync(id,	currentUser);

				if	(!successful)

				{

								return	BadRequest("Could	not	mark	item	as	done.");

				}

				return	RedirectToAction("Index");

83

Using	identity	in	the	application

}

Both	service	methods	must	now	accept	an	 	ApplicationUser		parameter.

Update	the	interface	definition	in	 	ITodoItemService	:

Task<bool>	AddItemAsync(TodoItem	newItem,	ApplicationUser	user);

Task<bool>	MarkDoneAsync(Guid	id,	ApplicationUser	user);

And	finally,	update	the	service	method	implementations	in	the

	TodoItemService	.	In	 	AddItemAsync		method,	set	the	 	UserId		property

when	you	construct	a	 	new	TodoItem	:

public	async	Task<bool>	AddItemAsync(

				TodoItem	newItem,	ApplicationUser	user)

{

				newItem.Id	=	Guid.NewGuid();

				newItem.IsDone	=	false;

				newItem.DueAt	=	DateTimeOffset.Now.AddDays(3);

				newItem.UserId	=	user.Id;

				//	...

}

The	 	Where		clause	in	the	 	MarkDoneAsync		method	also	needs	to	check	for

the	user's	ID,	so	a	rogue	user	can't	complete	someone	else's	items	by

guessing	their	IDs:

public	async	Task<bool>	MarkDoneAsync(

				Guid	id,	ApplicationUser	user)

{

				var	item	=	await	_context.Items

								.Where(x	=>	x.Id	==	id	&&	x.UserId	==	user.Id)

								.SingleOrDefaultAsync();

				//	...

}

84

Using	identity	in	the	application

All	done!	Try	using	the	application	with	two	different	user	accounts.	The

to-do	items	stay	private	for	each	account.

85

Authorization	with	roles

Authorization	with	roles

Roles	are	a	common	approach	to	handling	authorization	and	permissions

in	a	web	application.	For	example,	it's	common	to	create	an

Administrator	role	that	gives	admin	users	more	permissions	or	power

than	normal	users.

In	this	project,	you'll	add	a	Manage	Users	page	that	only	administrators

can	see.	If	normal	users	try	to	access	it,	they'll	see	an	error.

Add	a	Manage	Users	page

First,	create	a	new	controller:

Controllers/ManageUsersController.cs

using	System;

using	System.Linq;

using	System.Threading.Tasks;

using	Microsoft.AspNetCore.Mvc;

using	Microsoft.AspNetCore.Authorization;

using	Microsoft.AspNetCore.Identity;

using	AspNetCoreTodo.Models;

using	Microsoft.EntityFrameworkCore;

namespace	AspNetCoreTodo.Controllers

{

				[Authorize(Roles	=	"Administrator")]

				public	class	ManageUsersController	:	Controller

				{

								private	readonly	UserManager<ApplicationUser>

												_userManager;

								public	ManageUsersController(

												UserManager<ApplicationUser>	userManager)

								{

												_userManager	=	userManager;

								}

86

Authorization	with	roles

								public	async	Task<IActionResult>	Index()

								{

												var	admins	=	(await	_userManager

																.GetUsersInRoleAsync("Administrator"))

																.ToArray();

												var	everyone	=	await	_userManager.Users

																.ToArrayAsync();

												var	model	=	new	ManageUsersViewModel

												{

																Administrators	=	admins,

																Everyone	=	everyone

												};

												return	View(model);

								}

				}

}

Setting	the	 	Roles		property	on	the	 	[Authorize]		attribute	will	ensure

that	the	user	must	be	logged	in	and	assigned	the	Administrator	role	in

order	to	view	the	page.

Next,	create	a	view	model:

Models/ManageUsersViewModel.cs

using	System.Collections.Generic;

using	AspNetCoreTodo.Models;

namespace	AspNetCoreTodo.Models

{

				public	class	ManageUsersViewModel

				{

								public	ApplicationUser[]	Administrators	{	get;	set;	}

								public	ApplicationUser[]	Everyone	{	get;	set;}

				}

}

87

Authorization	with	roles

Finally,	create	a	 	Views/ManageUsers		folder	and	a	view	for	the	 	Index	

action:

Views/ManageUsers/Index.cshtml

@model	ManageUsersViewModel

@{

				ViewData["Title"]	=	"Manage	users";

}

<h2>@ViewData["Title"]</h2>

<h3>Administrators</h3>

<table	class="table">

				<thead>

								<tr>

												<td>Id</td>

												<td>Email</td>

								</tr>

				</thead>

				@foreach	(var	user	in	Model.Administrators)

				{

								<tr>

												<td>@user.Id</td>

												<td>@user.Email</td>

								</tr>

				}

</table>

<h3>Everyone</h3>

<table	class="table">

				<thead>

								<tr>

												<td>Id</td>

												<td>Email</td>

								</tr>

				</thead>

				@foreach	(var	user	in	Model.Everyone)

88

Authorization	with	roles

				{

								<tr>

												<td>@user.Id</td>

												<td>@user.Email</td>

								</tr>

				}

</table>

Start	up	the	application	and	try	to	access	the	 	/ManageUsers		route	while

logged	in	as	a	normal	user.	You'll	see	this	access	denied	page:

That's	because	users	aren't	assigned	the	Administrator	role

automatically.

Create	a	test	administrator	account

For	obvious	security	reasons,	it	isn't	possible	for	anyone	to	register	a

new	administrator	account	themselves.	In	fact,	the	Administrator	role

doesn't	even	exist	in	the	database	yet!

You	can	add	the	Administrator	role	plus	a	test	administrator	account	to

the	database	the	first	time	the	application	starts	up.	Adding	first-time

data	to	the	database	is	called	initializing	or	seeding	the	database.

Create	a	new	class	in	the	root	of	the	project	called	 	SeedData	:

89

Authorization	with	roles

SeedData.cs

using	System;

using	System.Threading.Tasks;

using	AspNetCoreTodo.Models;

using	Microsoft.AspNetCore.Identity;

using	Microsoft.EntityFrameworkCore;

using	Microsoft.Extensions.DependencyInjection;

namespace	AspNetCoreTodo

{

				public	static	class	SeedData

				{

								public	static	async	Task	InitializeAsync(

												IServiceProvider	services)

								{

												var	roleManager	=	services

																.GetRequiredService<RoleManager<IdentityRole>>();

												await	EnsureRolesAsync(roleManager);

												var	userManager	=	services

																.GetRequiredService<UserManager<ApplicationUser>>(

);

												await	EnsureTestAdminAsync(userManager);

								}

				}

}

The	 	InitializeAsync()		method	uses	an	 	IServiceProvider		(the

collection	of	services	that	is	set	up	in	the	 	Startup.ConfigureServices()	

method)	to	get	the	 	RoleManager		and	 	UserManager		from	ASP.NET	Core

Identity.

Add	two	more	methods	below	the	 	InitializeAsync()		method.	First,	the

	EnsureRolesAsync()		method:

private	static	async	Task	EnsureRolesAsync(

				RoleManager<IdentityRole>	roleManager)

{

				var	alreadyExists	=	await	roleManager

								.RoleExistsAsync(Constants.AdministratorRole);

90

Authorization	with	roles

				if	(alreadyExists)	return;

				await	roleManager.CreateAsync(

								new	IdentityRole(Constants.AdministratorRole));

}

This	method	checks	to	see	if	an	 	Administrator		role	exists	in	the

database.	If	not,	it	creates	one.	Instead	of	repeatedly	typing	the	string

	"Administrator"	,	create	a	small	class	called	 	Constants		to	hold	the

value:

Constants.cs

namespace	AspNetCoreTodo

{

				public	static	class	Constants

				{

								public	const	string	AdministratorRole	=	"Administrator";

				}

}

If	you	want,	you	can	update	the	 	ManageUsersController		to	use

this	constant	value	as	well.

Next,	write	the	 	EnsureTestAdminAsync()		method:

SeedData.cs

private	static	async	Task	EnsureTestAdminAsync(

				UserManager<ApplicationUser>	userManager)

{

				var	testAdmin	=	await	userManager.Users

								.Where(x	=>	x.UserName	==	"[email protected]")

								.SingleOrDefaultAsync();

				if	(testAdmin	!=	null)	return;

				testAdmin	=	new	ApplicationUser

				{

91

Authorization	with	roles

								UserName	=	"[email protected]",

								Email	=	"[email protected]"

				};

				await	userManager.CreateAsync(

								testAdmin,	"NotSecure123!!");

				await	userManager.AddToRoleAsync(

								testAdmin,	Constants.AdministratorRole);

}

If	there	isn't	already	a	user	with	the	username	 	[email protected]		in	the

database,	this	method	will	create	one	and	assign	a	temporary	password.

After	you	log	in	for	the	first	time,	you	should	change	the	account's

password	to	something	secure!

Next,	you	need	to	tell	your	application	to	run	this	logic	when	it	starts	up.

Modify	 	Program.cs		and	update	 	Main()		to	call	a	new	method,

	InitializeDatabase()	:

Program.cs

public	static	void	Main(string[]	args)

{

				var	host	=	BuildWebHost(args);

				InitializeDatabase(host);

				host.Run();

}

Then,	add	the	new	method	to	the	class	below	 	Main()	:

private	static	void	InitializeDatabase(IWebHost	host)

{

				using	(var	scope	=	host.Services.CreateScope())

				{

								var	services	=	scope.ServiceProvider;

								try

								{

												SeedData.InitializeAsync(services).Wait();

								}

92

Authorization	with	roles

								catch	(Exception	ex)

								{

												var	logger	=	services

																.GetRequiredService<ILogger<Program>>();

												logger.LogError(ex,	"Error	occurred	seeding	the	DB.");

								}

				}

}

Add	this	 	using		statement	to	the	top	of	the	file:

using	Microsoft.Extensions.DependencyInjection;

This	method	gets	the	service	collection	that	 	SeedData.InitializeAsync()	

needs	and	then	runs	the	method	to	seed	the	database.	If	something	goes

wrong,	an	error	is	logged.

Because	 	InitializeAsync()		returns	a	 	Task	,	the	 	Wait()		method

must	be	used	to	make	sure	it	finishes	before	the	application	starts

up.	You'd	normally	use	 	await		for	this,	but	for	technical	reasons

you	can't	use	 	await		in	the	 	Program		class.	This	is	a	rare

exception.	You	should	use	 	await		everywhere	else!

When	you	start	the	application	next,	the	 	[email protected]		account	will

be	created	and	assigned	the	Administrator	role.	Try	logging	in	with	this

account,	and	navigating	to	 	http://localhost:5000/ManageUsers	.	You'll

see	a	list	of	all	users	registered	for	the	application.

As	an	extra	challenge,	try	adding	more	administration	features	to

this	page.	For	example,	you	could	add	a	button	that	gives	an

administrator	the	ability	to	delete	a	user	account.

Check	for	authorization	in	a	view

93

Authorization	with	roles

The	 	[Authorize]		attribute	makes	it	easy	to	perform	an	authorization

check	in	a	controller	or	action	method,	but	what	if	you	need	to	check

authorization	in	a	view?	For	example,	it	would	be	nice	to	display	a

"Manage	users"	link	in	the	navigation	bar	if	the	logged-in	user	is	an

administrator.

You	can	inject	the	 	UserManager		directly	into	a	view	to	do	these	types	of

authorization	checks.	To	keep	your	views	clean	and	organized,	create	a

new	partial	view	that	will	add	an	item	to	the	navbar	in	the	layout:

Views/Shared/_AdminActionsPartial.cshtml

@using	Microsoft.AspNetCore.Identity

@using	AspNetCoreTodo.Models

@inject	SignInManager<ApplicationUser>	signInManager

@inject	UserManager<ApplicationUser>	userManager

@if	(signInManager.IsSignedIn(User))

{

				var	currentUser	=	await	UserManager.GetUserAsync(User);

				var	isAdmin	=	currentUser	!=	null

								&&	await	userManager.IsInRoleAsync(

												currentUser,

												Constants.AdministratorRole);

				if	(isAdmin)

				{

								<ul	class="nav	navbar-nav	navbar-right">

												<li>

																<a	asp-controller="ManageUsers"	

																			asp-action="Index">

																			Manage	Users

																</a>

												</li>

								</ul>

				}

}

94

Authorization	with	roles

It's	conventional	to	name	shared	partial	views	starting	with	an	 	_	

underscore,	but	it's	not	required.

This	partial	view	first	uses	the	 	SignInManager		to	quickly	determine

whether	the	user	is	logged	in.	If	they	aren't,	the	rest	of	the	view	code	can

be	skipped.	If	there	is	a	logged-in	user,	the	 	UserManager		is	used	to	look

up	their	details	and	perform	an	authorization	check	with

	IsInRoleAsync()	.	If	all	checks	succeed	and	the	user	is	an	adminstrator,	a

Manage	users	link	is	added	to	the	navbar.

To	include	this	partial	in	the	main	layout,	edit	 	_Layout.cshtml		and	add	it

in	the	navbar	section:

Views/Shared/_Layout.cshtml

<div	class="navbar-collapse	collapse">

				<ul	class="nav	navbar-nav">

								<!--	existing	code	here	-->

				</ul>

				@await	Html.PartialAsync("_LoginPartial")

				@await	Html.PartialAsync("_AdminActionsPartial")

</div>

When	you	log	in	with	an	administrator	account,	you'll	now	see	a	new

item	on	the	top	right:

95

More	resources

More	resources

ASP.NET	Core	Identity	helps	you	add	security	and	identity	features	like

login	and	registration	to	your	application.	The	 	dotnet	new		templates

give	you	pre-built	views	and	controllers	that	handle	these	common

scenarios	so	you	can	get	up	and	running	quickly.

There's	much	more	that	ASP.NET	Core	Identity	can	do,	such	as	password

reset	and	social	login.	The	documentation	available	at	http://docs.asp.net

is	a	fantastic	resource	for	learning	how	to	add	these	features.

Alternatives	to	ASP.NET	Core	Identity

ASP.NET	Core	Identity	isn't	the	only	way	to	add	identity	functionality.

Another	approach	is	to	use	a	cloud-hosted	identity	service	like	Azure

Active	Directory	B2C	or	Okta	to	handle	identity	for	your	application.	You

can	think	of	these	options	as	part	of	a	progression:

Do-it-yourself	security:	Not	recommended,	unless	you	are	a

security	expert!

ASP.NET	Core	Identity:	You	get	a	lot	of	code	for	free	with	the

templates,	which	makes	it	pretty	easy	to	get	started.	You'll	still	need

to	write	some	code	for	more	advanced	scenarios,	and	maintain	a

database	to	store	user	information.

Cloud-hosted	identity	services.	The	service	handles	both	simple	and

advanced	scenarios	(multi-factor	authentication,	account	recovery,

federation),	and	significantly	reduces	the	amount	of	code	you	need

to	write	and	maintain	in	your	application.	Plus,	sensitive	user	data

isn't	stored	in	your	own	database.

96

More	resources

For	this	project,	ASP.NET	Core	Identity	is	a	great	fit.	For	more	complex

projects,	I'd	recommend	doing	some	research	and	experimenting	with

both	options	to	understand	which	is	best	for	your	use	case.

97

Automated	testing

Automated	testing

Writing	tests	is	an	important	part	of	building	any	application.	Testing

your	code	helps	you	find	and	avoid	bugs,	and	makes	it	easier	to	refactor

your	code	later	without	breaking	functionality	or	introducing	new

problems.

In	this	chapter	you'll	learn	how	to	write	both	unit	tests	and	integration

tests	that	exercise	your	ASP.NET	Core	application.	Unit	tests	are	small

tests	that	make	sure	a	single	method	or	chunk	of	logic	works	properly.

Integration	tests	(sometimes	called	functional	tests)	are	larger	tests	that

simulate	real-world	scenarios	and	test	multiple	layers	or	parts	of	your

application.

98

Unit	testing

Unit	testing

Unit	tests	are	small,	short	tests	that	check	the	behavior	of	a	single

method	or	class.	When	the	code	you're	testing	relies	on	other	methods

or	classes,	unit	tests	rely	on	mocking	those	other	classes	so	that	the	test

only	focuses	on	one	thing	at	a	time.

For	example,	the	 	TodoController		class	has	two	dependencies:	an

	ITodoItemService		and	the	 	UserManager	.	The	 	TodoItemService	,	in	turn,

depends	on	the	 	ApplicationDbContext	.	(The	idea	that	you	can	draw	a

line	from	 	TodoController		>	 	TodoItemService		>	 	ApplicationDbContext		is

called	a	dependency	graph).

When	the	application	runs	normally,	the	ASP.NET	Core	service	container

and	dependency	injection	system	injects	each	of	those	objects	into	the

dependency	graph	when	the	 	TodoController		or	the	 	TodoItemService		is

created.

When	you	write	a	unit	test,	on	the	other	hand,	you	have	to	handle	the

dependency	graph	yourself.	It's	typical	to	provide	test-only	or	"mocked"

versions	of	those	dependencies.	This	means	you	can	isolate	just	the	logic

in	the	class	or	method	you	are	testing.	(This	is	important!	If	you're	testing

a	service,	you	don't	want	to	also	be	accidentally	writing	to	your

database.)

Create	a	test	project

It's	a	best	practice	to	create	a	separate	project	for	your	tests,	so	they	are

kept	separate	from	your	application	code.	The	new	test	project	should

live	in	a	directory	that's	next	to	(not	inside)	your	main	project's	directory.

99

Unit	testing

If	you're	currently	in	your	project	directory,	 	cd		up	one	level.	(This	root

directory	will	also	be	called	 	AspNetCoreTodo	).	Then	use	this	command	to

scaffold	a	new	test	project:

dotnet	new	xunit	-o	AspNetCoreTodo.UnitTests

xUnit.NET	is	a	popular	test	framework	for	.NET	code	that	can	be	used	to

write	both	unit	and	integration	tests.	Like	everything	else,	it's	a	set	of

NuGet	packages	that	can	be	installed	in	any	project.	The	 	dotnet	new

xunit		template	already	includes	everything	you	need.

Your	directory	structure	should	now	look	like	this:

AspNetCoreTodo/

				AspNetCoreTodo/

								AspNetCoreTodo.csproj

								Controllers/

								(etc...)

				AspNetCoreTodo.UnitTests/

								AspNetCoreTodo.UnitTests.csproj

Since	the	test	project	will	use	the	classes	defined	in	your	main	project,

you'll	need	to	add	a	reference	to	the	 	AspNetCoreTodo		project:

dotnet	add	reference	../AspNetCoreTodo/AspNetCoreTodo.csproj

Delete	the	 	UnitTest1.cs		file	that's	automatically	created.	You're	ready

to	write	your	first	test.

If	you're	using	Visual	Studio	Code,	you	may	need	to	close	and

reopen	the	Visual	Studio	Code	window	to	get	code	completion

working	in	the	new	project.

Write	a	service	test

100

Unit	testing

Take	a	look	at	the	logic	in	the	 	AddItemAsync()		method	of	the

	TodoItemService	:

public	async	Task<bool>	AddItemAsync(

				TodoItem	newItem,	ApplicationUser	user)

{

				newItem.Id	=	Guid.NewGuid();

				newItem.IsDone	=	false;

				newItem.DueAt	=	DateTimeOffset.Now.AddDays(3);

				newItem.UserId	=	user.Id;

				_context.Items.Add(newItem);

				var	saveResult	=	await	_context.SaveChangesAsync();

				return	saveResult	==	1;

}

This	method	makes	a	number	of	decisions	or	assumptions	about	the	new

item	(in	other	words,	performs	business	logic	on	the	new	item)	before	it

actually	saves	it	to	the	database:

The	 	UserId		property	should	be	set	to	the	user's	ID

New	items	should	always	be	incomplete	( 	IsDone	=	false	)

The	title	of	the	new	item	should	be	copied	from	 	newItem.Title	

New	items	should	always	be	due	3	days	from	now

Imagine	if	you	or	someone	else	refactored	the	 	AddItemAsync()		method

and	forgot	about	part	of	this	business	logic.	The	behavior	of	your

application	could	change	without	you	realizing	it!	You	can	prevent	this	by

writing	a	test	that	double-checks	that	this	business	logic	hasn't	changed

(even	if	the	method's	internal	implementation	changes).

It	might	seem	unlikely	now	that	you	could	introduce	a	change	in

business	logic	without	realizing	it,	but	it	becomes	much	harder	to

keep	track	of	decisions	and	assumptions	in	a	large,	complex

project.	The	larger	your	project	is,	the	more	important	it	is	to	have

automated	checks	that	make	sure	nothing	has	changed!

101

Unit	testing

To	write	a	unit	test	that	will	verify	the	logic	in	the	 	TodoItemService	,

create	a	new	class	in	your	test	project:

AspNetCoreTodo.UnitTests/TodoItemServiceShould.cs

using	System;

using	System.Threading.Tasks;

using	AspNetCoreTodo.Data;

using	AspNetCoreTodo.Models;

using	AspNetCoreTodo.Services;

using	Microsoft.EntityFrameworkCore;

using	Xunit;

namespace	AspNetCoreTodo.UnitTests

{

				public	class	TodoItemServiceShould

				{

								[Fact]

								public	async	Task	AddNewItemAsIncompleteWithDueDate()

								{

												//	...

								}

				}

}

There	are	many	different	ways	of	naming	and	organizing	tests,	all

with	different	pros	and	cons.	I	like	postfixing	my	test	classes	with

	Should		to	create	a	readable	sentence	with	the	test	method	name,

but	feel	free	to	use	your	own	style!

The	 	[Fact]		attribute	comes	from	the	xUnit.NET	package,	and	it	marks

this	method	as	a	test	method.

The	 	TodoItemService		requires	an	 	ApplicationDbContext	,	which	is

normally	connected	to	your	database.	You	won't	want	to	use	that	for

tests.	Instead,	you	can	use	Entity	Framework	Core's	in-memory	database

provider	in	your	test	code.	Since	the	entire	database	exists	in	memory,

102

Unit	testing

it's	wiped	out	every	time	the	test	is	restarted.	And,	since	it's	a	proper

Entity	Framework	Core	provider,	the	 	TodoItemService		won't	know	the

difference!

Use	a	 	DbContextOptionsBuilder		to	configure	the	in-memory	database

provider,	and	then	make	a	call	to	 	AddItemAsync()	:

var	options	=	new	DbContextOptionsBuilder<ApplicationDbContext>()

				.UseInMemoryDatabase(databaseName:	"Test_AddNewItem").Options;

//	Set	up	a	context	(connection	to	the	"DB")	for	writing

using	(var	context	=	new	ApplicationDbContext(options))

{

				var	service	=	new	TodoItemService(context);

				var	fakeUser	=	new	ApplicationUser

				{

								Id	=	"fake-000",

								UserName	=	"[email protected]"

				};

				await	service.AddItemAsync(new	TodoItem

				{

								Title	=	"Testing?"

				},	fakeUser);

}

The	last	line	creates	a	new	to-do	item	called	 	Testing?	,	and	tells	the

service	to	save	it	to	the	(in-memory)	database.

To	verify	that	the	business	logic	ran	correctly,	write	some	more	code

below	the	existing	 	using		block:

//	Use	a	separate	context	to	read	data	back	from	the	"DB"

using	(var	context	=	new	ApplicationDbContext(options))

{

				var	itemsInDatabase	=	await	context

								.Items.CountAsync();

				Assert.Equal(1,	itemsInDatabase);

103

Unit	testing

				var	item	=	await	context.Items.FirstAsync();

				Assert.Equal("Testing?",	item.Title);

				Assert.Equal(false,	item.IsDone);

				//	Item	should	be	due	3	days	from	now	(give	or	take	a	second)

				var	difference	=	DateTimeOffset.Now.AddDays(3)	-	item.DueAt;

				Assert.True(difference	<	TimeSpan.FromSeconds(1));

}

The	first	assertion	is	a	sanity	check:	there	should	never	be	more	than	one

item	saved	to	the	in-memory	database.	Assuming	that's	true,	the	test

retrieves	the	saved	item	with	 	FirstAsync		and	then	asserts	that	the

properties	are	set	to	the	expected	values.

Both	unit	and	integration	tests	typically	follow	the	AAA	(Arrange-

Act-Assert)	pattern:	objects	and	data	are	set	up	first,	then	some

action	is	performed,	and	finally	the	test	checks	(asserts)	that	the

expected	behavior	occurred.

Asserting	a	datetime	value	is	a	little	tricky,	since	comparing	two	dates	for

equality	will	fail	if	even	the	millisecond	components	are	different.

Instead,	the	test	checks	that	the	 	DueAt		value	is	less	than	a	second	away

from	the	expected	value.

Run	the	test

On	the	terminal,	run	this	command	(make	sure	you're	still	in	the

	AspNetCoreTodo.UnitTests		directory):

dotnet	test

The	 	test		command	scans	the	current	project	for	tests	(marked	with

	[Fact]		attributes	in	this	case),	and	runs	all	the	tests	it	finds.	You'll	see

output	similar	to:

Starting	test	execution,	please	wait...

104

Unit	testing

	Discovering:	AspNetCoreTodo.UnitTests

	Discovered:		AspNetCoreTodo.UnitTests

	Starting:				AspNetCoreTodo.UnitTests

	Finished:				AspNetCoreTodo.UnitTests

Total	tests:	1.	Passed:	1.	Failed:	0.	Skipped:	0.

Test	Run	Successful.

Test	execution	time:	1.9074	Seconds

You	now	have	one	test	providing	test	coverage	of	the	 	TodoItemService	.

As	an	extra	challenge,	try	writing	unit	tests	that	ensure:

The	 	MarkDoneAsync()		method	returns	false	if	it's	passed	an	ID	that

doesn't	exist

The	 	MarkDoneAsync()		method	returns	true	when	it	makes	a	valid

item	as	complete

The	 	GetIncompleteItemsAsync()		method	returns	only	the	items

owned	by	a	particular	user

105

Integration	testing

Integration	testing

Compared	to	unit	tests,	integration	tests	are	much	larger	in	scope.

exercise	the	whole	application	stack.	Instead	of	isolating	one	class	or

method,	integration	tests	ensure	that	all	of	the	components	of	your

application	are	working	together	properly:	routing,	controllers,	services,

database	code,	and	so	on.

Integration	tests	are	slower	and	more	involved	than	unit	tests,	so	it's

common	for	a	project	to	have	lots	of	small	unit	tests	but	only	a	handful

of	integration	tests.

In	order	to	test	the	whole	stack	(including	controller	routing),	integration

tests	typically	make	HTTP	calls	to	your	application	just	like	a	web

browser	would.

To	write	integration	tests	that	make	HTTP	requests,	you	could	manually

start	your	application	and	tests	at	the	same	time,	and	write	your	tests	to

make	requests	to	 	http://localhost:5000	.	ASP.NET	Core	provides	a

nicer	way	to	host	your	application	for	testing,	however:	the	 	TestServer	

class.	 	TestServer		can	host	your	application	for	the	duration	of	the	test,

and	then	stop	it	automatically	when	the	test	is	complete.

Create	a	test	project

If	you're	currently	in	your	project	directory,	 	cd		up	one	level	to	the	root

	AspNetCoreTodo		directory.	Use	this	command	to	scaffold	a	new	test

project:

dotnet	new	xunit	-o	AspNetCoreTodo.IntegrationTests

Your	directory	structure	should	now	look	like	this:

106

Integration	testing

AspNetCoreTodo/

				AspNetCoreTodo/

								AspNetCoreTodo.csproj

								Controllers/

								(etc...)

				AspNetCoreTodo.UnitTests/

								AspNetCoreTodo.UnitTests.csproj

				AspNetCoreTodo.IntegrationTests/

								AspNetCoreTodo.IntegrationTests.csproj

If	you	prefer,	you	can	keep	your	unit	tests	and	integration	tests	in

the	same	project.	For	large	projects,	it's	common	to	split	them	up

so	it's	easy	to	run	them	separately.

Since	the	test	project	will	use	the	classes	defined	in	your	main	project,

you'll	need	to	add	a	reference	to	the	main	project:

dotnet	add	reference	../AspNetCoreTodo/AspNetCoreTodo.csproj

You'll	also	need	to	add	the	 	Microsoft.AspNetCore.TestHost		NuGet

package:

dotnet	add	package	Microsoft.AspNetCore.TestHost

Delete	the	 	UnitTest1.cs		file	that's	created	by	 	dotnet	new	.	You're	ready

to	write	an	integration	test.

Write	an	integration	test

There	are	a	few	things	that	need	to	be	configured	on	the	test	server

before	each	test.	Instead	of	cluttering	the	test	with	this	setup	code,	you

can	keep	this	setup	in	a	separate	class.	Create	a	new	class	called

	TestFixture	:

107

Integration	testing

AspNetCoreTodo.IntegrationTests/TestFixture.cs

using	System;

using	System.Collections.Generic;

using	System.IO;

using	System.Net.Http;

using	Microsoft.AspNetCore.Hosting;

using	Microsoft.AspNetCore.TestHost;

using	Microsoft.Extensions.Configuration;

namespace	AspNetCoreTodo.IntegrationTests

{

				public	class	TestFixture	:	IDisposable		

				{

								private	readonly	TestServer	_server;

								public	HttpClient	Client	{	get;	}

								public	TestFixture()

								{

												var	builder	=	new	WebHostBuilder()

																.UseStartup<AspNetCoreTodo.Startup>()

																.ConfigureAppConfiguration((context,	config)	=>

																{

																				config.SetBasePath(Path.Combine(

																								Directory.GetCurrentDirectory(),

																								"..\\..\\..\\..\\AspNetCoreTodo"));

																				config.AddJsonFile("appsettings.json");

																});

												_server	=	new	TestServer(builder);

												Client	=	_server.CreateClient();

												Client.BaseAddress	=	new	Uri("http://localhost:8888");

								}

								public	void	Dispose()

								{

												Client.Dispose();

												_server.Dispose();

								}

				}

}

108

Integration	testing

This	class	takes	care	of	setting	up	a	 	TestServer	,	and	will	help	keep	the

tests	themselves	clean	and	tidy.

Now	you're	(really)	ready	to	write	an	integration	test.	Create	a	new	class

called	 	TodoRouteShould	:

AspNetCoreTodo.IntegrationTests/TodoRouteShould.cs

using	System.Net;

using	System.Net.Http;

using	System.Threading.Tasks;

using	Xunit;

namespace	AspNetCoreTodo.IntegrationTests

{

				public	class	TodoRouteShould	:	IClassFixture<TestFixture>

				{

								private	readonly	HttpClient	_client;

								public	TodoRouteShould(TestFixture	fixture)

								{

												_client	=	fixture.Client;

								}

								[Fact]

								public	async	Task	ChallengeAnonymousUser()

								{

												//	Arrange

												var	request	=	new	HttpRequestMessage(

																HttpMethod.Get,	"/todo");

												//	Act:	request	the	/todo	route

												var	response	=	await	_client.SendAsync(request);

												//	Assert:	the	user	is	sent	to	the	login	page

												Assert.Equal(

																HttpStatusCode.Redirect,

																response.StatusCode);

												Assert.Equal(

																"http://localhost:8888/Account"	+

109

Integration	testing

																"/Login?ReturnUrl=%2Ftodo",

																response.Headers.Location.ToString());

								}

				}

}

This	test	makes	an	anonymous	(not-logged-in)	request	to	the	 	/todo	

route	and	verifies	that	the	browser	is	redirected	to	the	login	page.

This	scenario	is	a	good	candidate	for	an	integration	test,	because	it

involves	multiple	components	of	the	application:	the	routing	system,	the

controller,	the	fact	that	the	controller	is	marked	with	 	[Authorize]	,	and

so	on.	It's	also	a	good	test	because	it	ensures	you	won't	ever	accidentally

remove	the	 	[Authorize]		attribute	and	make	the	to-do	view	accessible

to	everyone.

Run	the	test

Run	the	test	in	the	terminal	with	 	dotnet	test	.	If	everything's	working

right,	you'll	see	a	success	message:

Starting	test	execution,	please	wait...

	Discovering:	AspNetCoreTodo.IntegrationTests

	Discovered:		AspNetCoreTodo.IntegrationTests

	Starting:				AspNetCoreTodo.IntegrationTests

	Finished:				AspNetCoreTodo.IntegrationTests

Total	tests:	1.	Passed:	1.	Failed:	0.	Skipped:	0.

Test	Run	Successful.

Test	execution	time:	2.0588	Seconds

Wrap	up

110

Integration	testing

Testing	is	a	broad	topic,	and	there's	much	more	to	learn.	This	chapter

doesn't	touch	on	UI	testing	or	testing	frontend	(JavaScript)	code,	which

probably	deserve	entire	books	of	their	own.	You	should,	however,	have

the	skills	and	base	knowledge	you	need	to	learn	more	about	testing	and

to	practice	writing	tests	for	your	own	applications.

The	ASP.NET	Core	documentation	(https://docs.asp.net)	and	Stack

Overflow	are	great	resources	for	learning	more	and	finding	answers

when	you	get	stuck.

111

Deploy	the	application

Deploy	the	application

You've	come	a	long	way,	but	you're	not	quite	done	yet.	Once	you've

created	a	great	application,	you	need	to	share	it	with	the	world!

Because	ASP.NET	Core	applications	can	run	on	Windows,	Mac,	or	Linux,

there	are	a	number	of	different	ways	you	can	deploy	your	application.	In

this	chapter,	I'll	show	you	the	most	common	(and	easiest)	ways	to	go	live.

Deployment	options

ASP.NET	Core	applications	are	typically	deployed	to	one	of	these

environments:

A	Docker	host.	Any	machine	capable	of	hosting	Docker	containers

can	be	used	to	host	an	ASP.NET	Core	application.	Creating	a	Docker

image	is	a	very	quick	way	to	get	your	application	deployed,

especially	if	you're	familiar	with	Docker.	(If	you're	not,	don't	worry!

I'll	cover	the	steps	later.)

Azure.	Microsoft	Azure	has	native	support	for	ASP.NET	Core

applications.	If	you	have	an	Azure	subscription,	you	just	need	to

create	a	Web	App	and	upload	your	project	files.	I'll	cover	how	to	do

this	with	the	Azure	CLI	in	the	next	section.

Linux	(with	Nginx).	If	you	don't	want	to	go	the	Docker	route,	you

can	still	host	your	application	on	any	Linux	server	(this	includes

Amazon	EC2	and	DigitalOcean	virtual	machines).	It's	typical	to	pair

ASP.NET	Core	with	the	Nginx	reverse	proxy.	(More	about	Nginx

below.)

112

Deploy	the	application

Windows.	You	can	use	the	IIS	web	server	on	Windows	to	host

ASP.NET	Core	applications.	It's	usually	easier	(and	cheaper)	to	just

deploy	to	Azure,	but	if	you	prefer	managing	Windows	servers

yourself,	it'll	work	just	fine.

Kestrel	and	reverse	proxies

If	you	don't	care	about	the	guts	of	hosting	ASP.NET	Core

applications	and	just	want	the	step-by-step	instructions,	feel	free

to	skip	to	one	of	the	next	two	sections.

ASP.NET	Core	includes	a	fast,	lightweight	web	server	called	Kestrel.	It's

the	server	you've	been	using	every	time	you	ran	 	dotnet	run		and

browsed	to	 	http://localhost:5000	.	When	you	deploy	your	application

to	a	production	environment,	it'll	still	use	Kestrel	behind	the	scenes.

However,	it's	recommended	that	you	put	a	reverse	proxy	in	front	of

Kestrel,	because	Kestrel	doesn't	yet	have	load	balancing	and	other

features	that	more	mature	web	servers	have.

On	Linux	(and	in	Docker	containers),	you	can	use	Nginx	or	the	Apache

web	server	to	receive	incoming	requests	from	the	internet	and	route

them	to	your	application	hosted	with	Kestrel.	If	you're	on	Windows,	IIS

does	the	same	thing.

If	you're	using	Azure	to	host	your	application,	this	is	all	done	for	you

automatically.	I'll	cover	setting	up	Nginx	as	a	reverse	proxy	in	the	Docker

section.

113

Deploy	to	Azure

Deploy	to	Azure

Deploying	your	ASP.NET	Core	application	to	Azure	only	takes	a	few

steps.	You	can	do	it	through	the	Azure	web	portal,	or	on	the	command

line	using	the	Azure	CLI.	I'll	cover	the	latter.

What	you'll	need

Git	(use	 	git	--version		to	make	sure	it's	installed)

The	Azure	CLI	(follow	the	install	instructions	at

https://github.com/Azure/azure-cli)

An	Azure	subscription	(the	free	subscription	is	fine)

A	deployment	configuration	file	in	your	project	root

Create	a	deployment	configuration	file

Since	there	are	multiple	projects	in	your	directory	structure	(the	web

application,	and	two	test	projects),	Azure	won't	know	which	one	to

publish.	To	fix	this,	create	a	file	called	 	.deployment		at	the	very	top	of

your	directory	structure:

.deployment

[config]

project	=	AspNetCoreTodo/AspNetCoreTodo.csproj

Make	sure	you	save	the	file	as	 	.deployment		with	no	other	parts	to	the

name.	(On	Windows,	you	may	need	to	put	quotes	around	the	filename,

like	 	".deployment"	,	to	prevent	a	 	.txt		extension	from	being	added.)

If	you	 	ls		or	 	dir		in	your	top-level	directory,	you	should	see	these

items:

114

Deploy	to	Azure

.deployment

AspNetCoreTodo

AspNetCoreTodo.IntegrationTests

AspNetCoreTodo.UnitTests

Set	up	the	Azure	resources

If	you	just	installed	the	Azure	CLI	for	the	first	time,	run

az	login

and	follow	the	prompts	to	log	in	on	your	machine.	Then,	create	a	new

Resource	Group	for	this	application:

az	group	create	-l	westus	-n	AspNetCoreTodoGroup

This	creates	a	Resource	Group	in	the	West	US	region.	If	you're	located

far	away	from	the	western	US,	use	 	az	account	list-locations		to	get	a

list	of	locations	and	find	one	closer	to	you.

Next,	create	an	App	Service	plan	in	the	group	you	just	created:

az	appservice	plan	create	-g	AspNetCoreTodoGroup	-n	AspNetCoreTodo

Plan	--sku	F1

F1	is	the	free	app	plan.	If	you	want	to	use	a	custom	domain	name

with	your	app,	use	the	D1	($10/month)	plan	or	higher.

Now	create	a	Web	App	in	the	App	Service	plan:

az	webapp	create	-g	AspNetCoreTodoGroup	-p	AspNetCoreTodoPlan	-n	M

yTodoApp

115

Deploy	to	Azure

The	name	of	the	app	( 	MyTodoApp		above)	must	be	globally	unique	in

Azure.	Once	the	app	is	created,	it	will	have	a	default	URL	in	the	format:

http://mytodoapp.azurewebsites.net

Deploy	your	project	files	to	Azure

You	can	use	Git	to	push	your	application	files	up	to	the	Azure	Web	App.

If	your	local	directory	isn't	already	tracked	as	a	Git	repo,	run	these

commands	to	set	it	up:

git	init

git	add	.

git	commit	-m	"First	commit!"

Next,	create	an	Azure	username	and	password	for	deployment:

az	webapp	deployment	user	set	--user-name	nate

Follow	the	instructions	to	create	a	password.	Then	use	 	config-local-

git		to	spit	out	a	Git	URL:

az	webapp	deployment	source	config-local-git	-g	AspNetCoreTodoGrou

p	-n	MyTodoApp	--out	tsv

https://[email protected]/MyTodoApp.git

Copy	the	URL	to	the	clipboard,	and	use	it	to	add	a	Git	remote	to	your

local	repository:

git	remote	add	azure	<paste>

You	only	need	to	do	these	steps	once.	Now,	whenever	you	want	to	push

your	application	files	to	Azure,	check	them	in	with	Git	and	run

116

Deploy	to	Azure

git	push	azure	master

You'll	see	a	stream	of	log	messages	as	the	application	is	deployed	to

Azure.

When	it's	complete,	browse	to	http://yourappname.azurewebsites.net	to

check	out	the	app!

117

Deploy	with	Docker

Deploy	with	Docker

If	you	aren't	using	a	platform	like	Azure,	containerization	technologies

like	Docker	can	make	it	easy	to	deploy	web	applications	to	your	own

servers.	Instead	of	spending	time	configuring	a	server	with	the

dependencies	it	needs	to	run	your	app,	copying	files,	and	restarting

processes,	you	can	simply	create	a	Docker	image	that	describes

everything	your	app	needs	to	run,	and	spin	it	up	as	a	container	on	any

Docker	host.

Docker	can	make	scaling	your	app	across	multiple	servers	easier,	too.

Once	you	have	an	image,	using	it	to	create	1	container	is	the	same

process	as	creating	100	containers.

Before	you	start,	you	need	the	Docker	CLI	installed	on	your

development	machine.	Search	for	"get	docker	for	(mac/windows/linux)"

and	follow	the	instructions	on	the	official	Docker	website.	You	can	verify

that	it's	installed	correctly	with

docker	version

Add	a	Dockerfile

The	first	thing	you'll	need	is	a	Dockerfile,	which	is	like	a	recipe	that	tells

Docker	what	your	application	needs	to	build	and	run.

Create	a	file	called	 	Dockerfile		(no	extension)	in	the	root,	top-level

	AspNetCoreTodo		folder.	Open	it	in	your	favorite	editor.	Write	the

following	line:

FROM	microsoft/dotnet:2.0-sdk	AS	build

118

Deploy	with	Docker

This	tells	Docker	to	use	the	 	microsoft/dotnet:2.0-sdk		image	as	a

starting	point.	This	image	is	published	by	Microsoft	and	contains	the

tools	and	dependencies	you	need	to	execute	 	dotnet	build		and	compile

your	application.	By	using	this	pre-built	image	as	a	starting	point,	Docker

can	optimize	the	image	produced	for	your	app	and	keep	it	small.

Next,	add	this	line:

COPY	AspNetCoreTodo/*.csproj	./app/AspNetCoreTodo/

The	 	COPY		command	copies	the	 	.csproj		project	file	into	the	image	at

the	path	 	/app/AspNetCoreTodo/	.	Note	that	none	of	the	actual	code	( 	.cs	

files)	have	been	copied	into	the	image	yet.	You'll	see	why	in	a	minute.

WORKDIR	/app/AspNetCoreTodo

RUN	dotnet	restore

	WORKDIR		is	the	Docker	equivalent	of	 	cd	.	This	means	any	commands

executed	next	will	run	from	inside	the	 	/app/AspNetCoreTodo		directory

that	the	 	COPY		command	created	in	the	last	step.

Running	the	 	dotnet	restore		command	restores	the	NuGet	packages

that	the	application	needs,	defined	in	the	 	.csproj		file.	By	restoring

packages	inside	the	image	before	adding	the	rest	of	the	code,	Docker	is

able	to	cache	the	restored	packages.	Then,	if	you	make	code	changes

(but	don't	change	the	packages	defined	in	the	project	file),	rebuilding	the

Docker	image	will	be	super	fast.

Now	it's	time	to	copy	the	rest	of	the	code	and	compile	the	application:

COPY	AspNetCoreTodo/.	./AspNetCoreTodo/

RUN	dotnet	publish	-o	out	/p:PublishWithAspNetCoreTargetManifest="

false"

119

Deploy	with	Docker

The	 	dotnet	publish		command	compiles	the	project,	and	the	 	-o	out	

flag	puts	the	compiled	files	in	a	directory	called	 	out	.

These	compiled	files	will	be	used	to	run	the	application	with	the	final	few

commands:

FROM	microsoft/dotnet:2.0-runtime	AS	runtime

ENV	ASPNETCORE_URLS	http://+:80

WORKDIR	/app

COPY	--from=build	/app/AspNetCoreTodo/out	./

ENTRYPOINT	["dotnet",	"AspNetCoreTodo.dll"]

The	 	FROM		command	is	used	again	to	select	a	smaller	image	that	only	has

the	dependencies	needed	to	run	the	application.	The	 	ENV		command	is

used	to	set	environment	variables	in	the	container,	and	the

	ASPNETCORE_URLS		environment	variable	tells	ASP.NET	Core	which

network	interface	and	port	it	should	bind	to	(in	this	case,	port	80).

The	 	ENTRYPOINT		command	lets	Docker	know	that	the	container	should

be	started	as	an	executable	by	running	 	dotnet	AspNetCoreTodo.dll	.	This

tells	 	dotnet		to	start	up	your	application	from	the	compiled	file	created

by	 	dotnet	publish		earlier.	(When	you	do	 	dotnet	run		during

development,	you're	accomplishing	the	same	thing	in	one	step.)

The	full	Dockerfile	looks	like	this:

Dockerfile

FROM	microsoft/dotnet:2.0-sdk	AS	build

COPY	AspNetCoreTodo/*.csproj	./app/AspNetCoreTodo/

WORKDIR	/app/AspNetCoreTodo

RUN	dotnet	restore

COPY	AspNetCoreTodo/.	./

RUN	dotnet	publish	-o	out	/p:PublishWithAspNetCoreTargetManifest="

false"

FROM	microsoft/dotnet:2.0-runtime	AS	runtime

120

Deploy	with	Docker

ENV	ASPNETCORE_URLS	http://+:80

WORKDIR	/app

COPY	--from=build	/app/AspNetCoreTodo/out	./

ENTRYPOINT	["dotnet",	"AspNetCoreTodo.dll"]

Create	an	image

Make	sure	the	Dockerfile	is	saved,	and	then	use	 	docker	build		to	create

an	image:

docker	build	-t	aspnetcoretodo	.

Don't	miss	the	trailing	period!	That	tells	Docker	to	look	for	a	Dockerfile

in	the	current	directory.

Once	the	image	is	created,	you	can	run	 	docker	images		to	to	list	all	the

images	available	on	your	local	machine.	To	test	it	out	in	a	container,	run

docker	run	--name	aspnetcoretodo_sample	--rm	-it	-p	8080:80	aspnet

coretodo

The	 	-it		flag	tells	Docker	to	run	the	container	in	interactive	mode

(outputting	to	the	terminal,	as	opposed	to	running	in	the	background).

When	you	want	to	stop	the	container,	press	Control-C.

Remember	the	 	ASPNETCORE_URLS		variable	that	told	ASP.NET	Core	to

listen	on	port	80?	The	 	-p	8080:80		option	tells	Docker	to	map	port	8080

on	your	machine	to	the	container's	port	80.	Open	up	your	browser	and

navigate	to	http://localhost:8080	to	see	the	application	running	in	the

container!

Set	up	Nginx

121

Deploy	with	Docker

At	the	beginning	of	this	chapter,	I	mentioned	that	you	should	use	a

reverse	proxy	like	Nginx	to	proxy	requests	to	Kestrel.	You	can	use

Docker	for	this,	too.

The	overall	architecture	will	consist	of	two	containers:	an	Nginx

container	listening	on	port	80,	forwarding	requests	to	the	container	you

just	built	that	hosts	your	application	with	Kestrel.

The	Nginx	container	needs	its	own	Dockerfile.	To	keep	it	from

conflicting	with	the	Dockerfile	you	just	created,	make	a	new	directory	in

the	web	application	root:

mkdir	nginx

Create	a	new	Dockerfile	and	add	these	lines:

nginx/Dockerfile

FROM	nginx

COPY	nginx.conf	/etc/nginx/nginx.conf

Next,	create	an	 	nginx.conf		file:

nginx/nginx.conf

events	{	worker_connections	1024;	}

http	{

				server	{

								listen	80;

								location	/	{

										proxy_pass	http://kestrel:80;

										proxy_http_version	1.1;

										proxy_set_header	Upgrade	$http_upgrade;

										proxy_set_header	Connection	'keep-alive';

										proxy_set_header	Host	$host;

										proxy_cache_bypass	$http_upgrade;

								}

122

Deploy	with	Docker

				}

}

This	configuration	file	tells	Nginx	to	proxy	incoming	requests	to

	http://kestrel:80	.	(You'll	see	why	 	kestrel		works	as	a	hostname	in	a

moment.)

When	you	make	deploy	your	application	to	a	production

environment,	you	should	add	the	 	server_name		directive	and

validate	and	restrict	the	host	header	to	known	good	values.	For

more	information,	see:

https://github.com/aspnet/Announcements/issues/295

Set	up	Docker	Compose

There's	one	more	file	to	create.	Up	in	the	root	directory,	create	 	docker-

compose.yml	:

docker-compose.yml

nginx:

				build:	./nginx

				links:

								-	kestrel:kestrel

				ports:

								-	"80:80"

kestrel:

				build:	.

				ports:

								-	"80"

Docker	Compose	is	a	tool	that	helps	you	create	and	run	multi-container

applications.	This	configuration	file	defines	two	containers:	 	nginx		from

the	 	./nginx/Dockerfile		recipe,	and	 	kestrel		from	the	 	./Dockerfile	

recipe.	The	containers	are	explicitly	linked	together	so	they	can

communicate.

123

Deploy	with	Docker

You	can	try	spinning	up	the	entire	multi-container	application	by	running:

docker-compose	up

Try	opening	a	browser	and	navigating	to	http://localhost	(port	80,	not

8080!).	Nginx	is	listening	on	port	80	(the	default	HTTP	port)	and	proxying

requests	to	your	ASP.NET	Core	application	hosted	by	Kestrel.

Set	up	a	Docker	server

Specific	setup	instructions	are	outside	the	scope	of	this	book,	but	any

modern	flavor	of	Linux	(like	Ubuntu)	can	be	used	to	set	up	a	Docker	host.

For	example,	you	could	create	a	virtual	machine	with	Amazon	EC2,	and

install	the	Docker	service.	You	can	search	for	"amazon	ec2	set	up

docker"	(for	example)	for	instructions.

I	like	using	DigitalOcean	because	they've	made	it	really	easy	to	get

started.	DigitalOcean	has	both	a	pre-built	Docker	virtual	machine,	and	in-

depth	tutorials	for	getting	Docker	up	and	running	(search	for

"digitalocean	docker").

124

Conclusion

Conclusion

Thanks	for	making	it	to	the	end	of	the	Little	ASP.NET	Core	Book!	If	this

book	was	helpful	(or	not),	I'd	love	to	hear	your	thoughts.	Send	me	your

comments	via	Twitter:	https://twitter.com/nbarbettini

How	to	learn	more

There's	a	lot	more	that	ASP.NET	Core	can	do	that	couldn't	fit	in	this

short	book,	including

Building	RESTful	APIs	and	microservices

Using	ASP.NET	Core	with	single-page	apps	like	Angular	and	React

Razor	Pages

Bundling	and	minifying	static	assets

WebSockets	and	SignalR

There	are	a	number	of	ways	you	can	learn	more:

The	ASP.NET	Core	documentation.	The	official	ASP.NET	Core

documentation	at	http://docs.asp.net	contains	a	number	of	in-depth

tutorials	covering	many	of	these	topics.	I'd	highly	recommend	it!

ASP.NET	Core	in	Action.	This	book	by	Andrew	Lock	is	a

comprehensive,	deep	dive	into	ASP.NET	Core.	You	can	get	it	from

Amazon	or	a	local	bookstore.

Courses	on	LinkedIn	Learning	and	Pluralsight.	If	you	learn	best	from

videos,	there	are	fantastic	courses	available	on	Pluralsight	and

LinkedIn	Learning	(including	some	by	yours	truly).	If	you	don't	have

an	account	and	need	a	coupon,	send	me	an	email:

[email protected].

125

Conclusion

Nate's	blog.	I	also	write	about	ASP.NET	Core	and	more	on	my	blog

at	https://www.recaffeinate.co.

Happy	coding!

About	the	author

Hey,	I'm	Nate!	I	wrote	the	Little	ASP.NET	Core	Book	in	a	long,	caffeine-

fueled	weekend	because	I	love	the	.NET	community	and	wanted	to	give

back	in	my	own	little	way.	I	hope	it	helped	you	learn	something	new!

You	can	stay	in	touch	with	me	on	Twitter	(@nbarbettini)	or	on	my	blog

(https://www.recaffeinate.co).	You	can	also	reach	me	via	email	at

[email protected].

Special	thanks

To	Jennifer,	who	always	supports	my	crazy	ideas.

To	the	following	contributors	who	improved	the	Little	ASP.NET	Core

Book:

0xNF

Matt	Welke

To	these	amazing	polyglot	programmers	who	translated	the	Little

ASP.NET	Core	Book:

sahinyanlik	(Turkish)

windsting,	yuyi	(Simplified	Chinese)

Changelog

126

Conclusion

The	full,	detailed	changelog	is	always	available	here:

https://github.com/nbarbettini/little-aspnetcore-book/releases

1.1.0	(2018-05-03):	Significantly	reworked	the	Add	more	features	chapter

to	use	MVC	thorough	the	whole	stack	and	remove	the	AJAX	pattern.

Removed	Facebook	login	to	simplify	the	security	chapter	and	streamline

testing	and	deployment.	Updated	the	Docker	instructions	to	reflect	the

latest	best	practices.	Fixed	typos	and	added	suggestions	from	readers.

The	book	also	sports	a	new,	improved	cover	design!

1.0.4	(2018-01-15):	Added	explanation	of	service	container	lifecycles,

clarified	server	ports	and	the	-o	flag,	and	removed	semicolons	after	Razor

directives.	Corrected	Chinese	translation	author	credit.	Fixed	other	small

typos	and	issues	noticed	by	readers.

1.0.3	(2017-11-13):	Typo	fixes	and	small	improvements	suggested	by

readers.

1.0.2	(2017-10-20):	More	bug	fixes	and	small	improvements.	Added	link

to	translations.

1.0.1	(2017-09-23):	Bug	fixes	and	small	improvements.

1.0.0	(2017-09-18):	Initial	release.

127