├── .gitignore
├── README.md
├── Video 1 - GET
├── Begin
│ ├── API
│ │ ├── API.csproj
│ │ ├── ApplicationDbContext.cs
│ │ ├── Controllers
│ │ │ ├── PeopleController.cs
│ │ │ └── WeatherForecastController.cs
│ │ ├── Program.cs
│ │ ├── Properties
│ │ │ └── launchSettings.json
│ │ ├── Startup.cs
│ │ ├── WeatherForecast.cs
│ │ ├── appsettings.Development.json
│ │ └── appsettings.json
│ ├── Common
│ │ ├── Common.csproj
│ │ └── Person.cs
│ ├── HttpClientTutorial.sln
│ └── TheConsole
│ │ ├── Program.cs
│ │ └── TheConsole.csproj
└── End
│ ├── API
│ ├── API.csproj
│ ├── ApplicationDbContext.cs
│ ├── Controllers
│ │ ├── PeopleController.cs
│ │ └── WeatherForecastController.cs
│ ├── Program.cs
│ ├── Properties
│ │ └── launchSettings.json
│ ├── Startup.cs
│ ├── WeatherForecast.cs
│ ├── appsettings.Development.json
│ └── appsettings.json
│ ├── Common
│ ├── Common.csproj
│ └── Person.cs
│ ├── HttpClientTutorial.sln
│ └── TheConsole
│ ├── Program.cs
│ └── TheConsole.csproj
├── Video 2 - POST
├── Begin
│ ├── API
│ │ ├── API.csproj
│ │ ├── ApplicationDbContext.cs
│ │ ├── Controllers
│ │ │ ├── PeopleController.cs
│ │ │ └── WeatherForecastController.cs
│ │ ├── Program.cs
│ │ ├── Properties
│ │ │ └── launchSettings.json
│ │ ├── Startup.cs
│ │ ├── WeatherForecast.cs
│ │ ├── appsettings.Development.json
│ │ └── appsettings.json
│ ├── Common
│ │ ├── Common.csproj
│ │ └── Person.cs
│ ├── HttpClientTutorial.sln
│ └── TheConsole
│ │ ├── Program.cs
│ │ └── TheConsole.csproj
└── End
│ ├── API
│ ├── API.csproj
│ ├── ApplicationDbContext.cs
│ ├── Controllers
│ │ ├── PeopleController.cs
│ │ └── WeatherForecastController.cs
│ ├── Program.cs
│ ├── Properties
│ │ └── launchSettings.json
│ ├── Startup.cs
│ ├── WeatherForecast.cs
│ ├── appsettings.Development.json
│ └── appsettings.json
│ ├── Common
│ ├── Common.csproj
│ └── Person.cs
│ ├── HttpClientTutorial.sln
│ └── TheConsole
│ ├── Program.cs
│ ├── TheConsole.csproj
│ └── Utils.cs
├── Video 3 - HTTP Request Headers
├── Begin
│ ├── API
│ │ ├── API.csproj
│ │ ├── ApplicationDbContext.cs
│ │ ├── Controllers
│ │ │ ├── AccountsController.cs
│ │ │ ├── PeopleController.cs
│ │ │ └── WeatherForecastController.cs
│ │ ├── Program.cs
│ │ ├── Properties
│ │ │ └── launchSettings.json
│ │ ├── Startup.cs
│ │ ├── WeatherForecast.cs
│ │ ├── appsettings.Development.json
│ │ └── appsettings.json
│ ├── Common
│ │ ├── Common.csproj
│ │ ├── Person.cs
│ │ ├── UserInfo.cs
│ │ ├── UserToken.cs
│ │ └── WeatherForecast.cs
│ ├── HttpClientTutorial.sln
│ └── TheConsole
│ │ ├── Program.cs
│ │ ├── TheConsole.csproj
│ │ └── Utils.cs
└── End
│ ├── API
│ ├── API.csproj
│ ├── ApplicationDbContext.cs
│ ├── Controllers
│ │ ├── AccountsController.cs
│ │ ├── PeopleController.cs
│ │ └── WeatherForecastController.cs
│ ├── Program.cs
│ ├── Properties
│ │ └── launchSettings.json
│ ├── Startup.cs
│ ├── WeatherForecast.cs
│ ├── appsettings.Development.json
│ └── appsettings.json
│ ├── Common
│ ├── Common.csproj
│ ├── Person.cs
│ ├── UserInfo.cs
│ ├── UserToken.cs
│ └── WeatherForecast.cs
│ ├── HttpClientTutorial.sln
│ └── TheConsole
│ ├── Program.cs
│ ├── TheConsole.csproj
│ └── Utils.cs
└── Video 4 - HTTP PUT and HTTP DELETE
├── Begin
├── API
│ ├── API.csproj
│ ├── ApplicationDbContext.cs
│ ├── Controllers
│ │ ├── PeopleController.cs
│ │ └── WeatherForecastController.cs
│ ├── Program.cs
│ ├── Properties
│ │ └── launchSettings.json
│ ├── Startup.cs
│ ├── WeatherForecast.cs
│ ├── appsettings.Development.json
│ └── appsettings.json
├── Common
│ ├── Common.csproj
│ ├── Person.cs
│ └── WeatherForecast.cs
├── HttpClientDemo.sln
└── TheConsole
│ ├── Program.cs
│ └── TheConsole.csproj
└── End
├── API
├── API.csproj
├── ApplicationDbContext.cs
├── Controllers
│ ├── PeopleController.cs
│ └── WeatherForecastController.cs
├── Program.cs
├── Properties
│ └── launchSettings.json
├── Startup.cs
├── WeatherForecast.cs
├── appsettings.Development.json
└── appsettings.json
├── Common
├── Common.csproj
├── Person.cs
└── WeatherForecast.cs
├── HttpClientDemo.sln
└── TheConsole
├── Program.cs
└── TheConsole.csproj
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | *.mp4
14 |
15 | # User-specific files (MonoDevelop/Xamarin Studio)
16 | *.userprefs
17 |
18 | # Mono auto generated files
19 | mono_crash.*
20 |
21 | # Build results
22 | [Dd]ebug/
23 | [Dd]ebugPublic/
24 | [Rr]elease/
25 | [Rr]eleases/
26 | x64/
27 | x86/
28 | [Aa][Rr][Mm]/
29 | [Aa][Rr][Mm]64/
30 | bld/
31 | [Bb]in/
32 | [Oo]bj/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # StyleCop
67 | StyleCopReport.xml
68 |
69 | # Files built by Visual Studio
70 | *_i.c
71 | *_p.c
72 | *_h.h
73 | *.ilk
74 | *.meta
75 | *.obj
76 | *.iobj
77 | *.pch
78 | *.pdb
79 | *.ipdb
80 | *.pgc
81 | *.pgd
82 | *.rsp
83 | *.sbr
84 | *.tlb
85 | *.tli
86 | *.tlh
87 | *.tmp
88 | *.tmp_proj
89 | *_wpftmp.csproj
90 | *.log
91 | *.vspscc
92 | *.vssscc
93 | .builds
94 | *.pidb
95 | *.svclog
96 | *.scc
97 |
98 | # Chutzpah Test files
99 | _Chutzpah*
100 |
101 | # Visual C++ cache files
102 | ipch/
103 | *.aps
104 | *.ncb
105 | *.opendb
106 | *.opensdf
107 | *.sdf
108 | *.cachefile
109 | *.VC.db
110 | *.VC.VC.opendb
111 |
112 | # Visual Studio profiler
113 | *.psess
114 | *.vsp
115 | *.vspx
116 | *.sap
117 |
118 | # Visual Studio Trace Files
119 | *.e2e
120 |
121 | # TFS 2012 Local Workspace
122 | $tf/
123 |
124 | # Guidance Automation Toolkit
125 | *.gpState
126 |
127 | # ReSharper is a .NET coding add-in
128 | _ReSharper*/
129 | *.[Rr]e[Ss]harper
130 | *.DotSettings.user
131 |
132 | # TeamCity is a build add-in
133 | _TeamCity*
134 |
135 | # DotCover is a Code Coverage Tool
136 | *.dotCover
137 |
138 | # AxoCover is a Code Coverage Tool
139 | .axoCover/*
140 | !.axoCover/settings.json
141 |
142 | # Coverlet is a free, cross platform Code Coverage Tool
143 | coverage*[.json, .xml, .info]
144 |
145 | # Visual Studio code coverage results
146 | *.coverage
147 | *.coveragexml
148 |
149 | # NCrunch
150 | _NCrunch_*
151 | .*crunch*.local.xml
152 | nCrunchTemp_*
153 |
154 | # MightyMoose
155 | *.mm.*
156 | AutoTest.Net/
157 |
158 | # Web workbench (sass)
159 | .sass-cache/
160 |
161 | # Installshield output folder
162 | [Ee]xpress/
163 |
164 | # DocProject is a documentation generator add-in
165 | DocProject/buildhelp/
166 | DocProject/Help/*.HxT
167 | DocProject/Help/*.HxC
168 | DocProject/Help/*.hhc
169 | DocProject/Help/*.hhk
170 | DocProject/Help/*.hhp
171 | DocProject/Help/Html2
172 | DocProject/Help/html
173 |
174 | # Click-Once directory
175 | publish/
176 |
177 | # Publish Web Output
178 | *.[Pp]ublish.xml
179 | *.azurePubxml
180 | # Note: Comment the next line if you want to checkin your web deploy settings,
181 | # but database connection strings (with potential passwords) will be unencrypted
182 | *.pubxml
183 | *.publishproj
184 |
185 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
186 | # checkin your Azure Web App publish settings, but sensitive information contained
187 | # in these scripts will be unencrypted
188 | PublishScripts/
189 |
190 | # NuGet Packages
191 | *.nupkg
192 | # NuGet Symbol Packages
193 | *.snupkg
194 | # The packages folder can be ignored because of Package Restore
195 | **/[Pp]ackages/*
196 | # except build/, which is used as an MSBuild target.
197 | !**/[Pp]ackages/build/
198 | # Uncomment if necessary however generally it will be regenerated when needed
199 | #!**/[Pp]ackages/repositories.config
200 | # NuGet v3's project.json files produces more ignorable files
201 | *.nuget.props
202 | *.nuget.targets
203 |
204 | # Microsoft Azure Build Output
205 | csx/
206 | *.build.csdef
207 |
208 | # Microsoft Azure Emulator
209 | ecf/
210 | rcf/
211 |
212 | # Windows Store app package directories and files
213 | AppPackages/
214 | BundleArtifacts/
215 | Package.StoreAssociation.xml
216 | _pkginfo.txt
217 | *.appx
218 | *.appxbundle
219 | *.appxupload
220 |
221 | # Visual Studio cache files
222 | # files ending in .cache can be ignored
223 | *.[Cc]ache
224 | # but keep track of directories ending in .cache
225 | !?*.[Cc]ache/
226 |
227 | # Others
228 | ClientBin/
229 | ~$*
230 | *~
231 | *.dbmdl
232 | *.dbproj.schemaview
233 | *.jfm
234 | *.pfx
235 | *.publishsettings
236 | orleans.codegen.cs
237 |
238 | # Including strong name files can present a security risk
239 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
240 | #*.snk
241 |
242 | # Since there are multiple workflows, uncomment next line to ignore bower_components
243 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
244 | #bower_components/
245 |
246 | # RIA/Silverlight projects
247 | Generated_Code/
248 |
249 | # Backup & report files from converting an old project file
250 | # to a newer Visual Studio version. Backup files are not needed,
251 | # because we have git ;-)
252 | _UpgradeReport_Files/
253 | Backup*/
254 | UpgradeLog*.XML
255 | UpgradeLog*.htm
256 | ServiceFabricBackup/
257 | *.rptproj.bak
258 |
259 | # SQL Server files
260 | *.mdf
261 | *.ldf
262 | *.ndf
263 |
264 | # Business Intelligence projects
265 | *.rdl.data
266 | *.bim.layout
267 | *.bim_*.settings
268 | *.rptproj.rsuser
269 | *- [Bb]ackup.rdl
270 | *- [Bb]ackup ([0-9]).rdl
271 | *- [Bb]ackup ([0-9][0-9]).rdl
272 |
273 | # Microsoft Fakes
274 | FakesAssemblies/
275 |
276 | # GhostDoc plugin setting file
277 | *.GhostDoc.xml
278 |
279 | # Node.js Tools for Visual Studio
280 | .ntvs_analysis.dat
281 | node_modules/
282 |
283 | # Visual Studio 6 build log
284 | *.plg
285 |
286 | # Visual Studio 6 workspace options file
287 | *.opt
288 |
289 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
290 | *.vbw
291 |
292 | # Visual Studio LightSwitch build output
293 | **/*.HTMLClient/GeneratedArtifacts
294 | **/*.DesktopClient/GeneratedArtifacts
295 | **/*.DesktopClient/ModelManifest.xml
296 | **/*.Server/GeneratedArtifacts
297 | **/*.Server/ModelManifest.xml
298 | _Pvt_Extensions
299 |
300 | # Paket dependency manager
301 | .paket/paket.exe
302 | paket-files/
303 |
304 | # FAKE - F# Make
305 | .fake/
306 |
307 | # CodeRush personal settings
308 | .cr/personal
309 |
310 | # Python Tools for Visual Studio (PTVS)
311 | __pycache__/
312 | *.pyc
313 |
314 | # Cake - Uncomment if you are using it
315 | # tools/**
316 | # !tools/packages.config
317 |
318 | # Tabs Studio
319 | *.tss
320 |
321 | # Telerik's JustMock configuration file
322 | *.jmconfig
323 |
324 | # BizTalk build output
325 | *.btp.cs
326 | *.btm.cs
327 | *.odx.cs
328 | *.xsd.cs
329 |
330 | # OpenCover UI analysis results
331 | OpenCover/
332 |
333 | # Azure Stream Analytics local run output
334 | ASALocalRun/
335 |
336 | # MSBuild Binary and Structured Log
337 | *.binlog
338 |
339 | # NVidia Nsight GPU debugger configuration file
340 | *.nvuser
341 |
342 | # MFractors (Xamarin productivity tool) working folder
343 | .mfractor/
344 |
345 | # Local History for Visual Studio
346 | .localhistory/
347 |
348 | # BeatPulse healthcheck temp database
349 | healthchecksdb
350 |
351 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
352 | MigrationBackup/
353 |
354 | # Ionide (cross platform F# VS Code tools) working folder
355 | .ionide/
356 |
357 | ##
358 | ## Visual studio for Mac
359 | ##
360 |
361 |
362 | # globs
363 | Makefile.in
364 | *.userprefs
365 | *.usertasks
366 | config.make
367 | config.status
368 | aclocal.m4
369 | install-sh
370 | autom4te.cache/
371 | *.tar.gz
372 | tarballs/
373 | test-results/
374 |
375 | # Mac bundle stuff
376 | *.dmg
377 | *.app
378 |
379 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
380 | # General
381 | .DS_Store
382 | .AppleDouble
383 | .LSOverride
384 |
385 | # Icon must end with two \r
386 | Icon
387 |
388 |
389 | # Thumbnails
390 | ._*
391 |
392 | # Files that might appear in the root of a volume
393 | .DocumentRevisions-V100
394 | .fseventsd
395 | .Spotlight-V100
396 | .TemporaryItems
397 | .Trashes
398 | .VolumeIcon.icns
399 | .com.apple.timemachine.donotpresent
400 |
401 | # Directories potentially created on remote AFP share
402 | .AppleDB
403 | .AppleDesktop
404 | Network Trash Folder
405 | Temporary Items
406 | .apdisk
407 |
408 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
409 | # Windows thumbnail cache files
410 | Thumbs.db
411 | ehthumbs.db
412 | ehthumbs_vista.db
413 |
414 | # Dump file
415 | *.stackdump
416 |
417 | # Folder config file
418 | [Dd]esktop.ini
419 |
420 | # Recycle Bin used on file shares
421 | $RECYCLE.BIN/
422 |
423 | # Windows Installer files
424 | *.cab
425 | *.msi
426 | *.msix
427 | *.msm
428 | *.msp
429 |
430 | # Windows shortcuts
431 | *.lnk
432 |
433 | # JetBrains Rider
434 | .idea/
435 | *.sln.iml
436 |
437 | ##
438 | ## Visual Studio Code
439 | ##
440 | .vscode/*
441 | !.vscode/settings.json
442 | !.vscode/tasks.json
443 | !.vscode/launch.json
444 | !.vscode/extensions.json
445 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Making video tutorials about HttpClient in C#
2 |
3 | Youtube playlist: https://www.youtube.com/playlist?list=PLiG4KxH00ZpnmuSsIrQ3IGTUUfl_Gl1AH
4 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/ApplicationDbContext.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.EntityFrameworkCore;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Diagnostics.CodeAnalysis;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace API
10 | {
11 | public class ApplicationDbContext : DbContext
12 | {
13 | public ApplicationDbContext([NotNull] DbContextOptions options) : base(options)
14 | {
15 | }
16 |
17 | public DbSet People { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/Controllers/PeopleController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Mvc;
3 | using Microsoft.EntityFrameworkCore;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace API.Controllers
10 | {
11 | [ApiController]
12 | [Route("api/people")]
13 | public class PeopleController: ControllerBase
14 | {
15 | private readonly ApplicationDbContext context;
16 |
17 | public PeopleController(ApplicationDbContext context)
18 | {
19 | this.context = context;
20 | }
21 |
22 | [HttpGet]
23 | public async Task>> Get()
24 | {
25 | //return NotFound();
26 | //return new List() { new Person() { Id = 1, Name = "Felipe"},
27 | //new Person(){Id = 2, Name = "Claudia"}};
28 | return await context.People.ToListAsync();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 |
8 | namespace API.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get()
28 | {
29 | var rng = new Random();
30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast
31 | {
32 | Date = DateTime.Now.AddDays(index),
33 | TemperatureC = rng.Next(-20, 55),
34 | Summary = Summaries[rng.Next(Summaries.Length)]
35 | })
36 | .ToArray();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Hosting;
2 | using Microsoft.Extensions.Configuration;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Logging;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace API
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:58393",
8 | "sslPort": 44337
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "API": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Builder;
2 | using Microsoft.AspNetCore.Hosting;
3 | using Microsoft.AspNetCore.HttpsPolicy;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.EntityFrameworkCore;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.DependencyInjection;
8 | using Microsoft.Extensions.Hosting;
9 | using Microsoft.Extensions.Logging;
10 | using Microsoft.OpenApi.Models;
11 | using System;
12 | using System.Collections.Generic;
13 | using System.Linq;
14 | using System.Threading.Tasks;
15 |
16 | namespace API
17 | {
18 | public class Startup
19 | {
20 | public Startup(IConfiguration configuration)
21 | {
22 | Configuration = configuration;
23 | }
24 |
25 | public IConfiguration Configuration { get; }
26 |
27 | // This method gets called by the runtime. Use this method to add services to the container.
28 | public void ConfigureServices(IServiceCollection services)
29 | {
30 | services.AddDbContext(options => options.UseInMemoryDatabase("mydatabase"));
31 | services.AddControllers();
32 | services.AddSwaggerGen(c =>
33 | {
34 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
35 | });
36 | }
37 |
38 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
39 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
40 | {
41 | if (env.IsDevelopment())
42 | {
43 | app.UseDeveloperExceptionPage();
44 | app.UseSwagger();
45 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
46 | }
47 |
48 | app.UseHttpsRedirection();
49 |
50 | app.UseRouting();
51 |
52 | app.UseAuthorization();
53 |
54 | app.UseEndpoints(endpoints =>
55 | {
56 | endpoints.MapControllers();
57 | });
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace API
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/Common/Person.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Common
4 | {
5 | public class Person
6 | {
7 | public int Id { get; set; }
8 | public string Name { get; set; }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/HttpClientTutorial.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30804.86
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheConsole", "TheConsole\TheConsole.csproj", "{3555DFEA-3E28-4519-95E3-5DA41622D4FF}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{D62139AC-C84A-4086-A4E2-EC9845A95CAF}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{058D1032-8480-4581-B6E3-EA7B704E233E}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {1A7A7613-556B-4F6B-8684-057AD8B535C0}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/TheConsole/Program.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net.Http;
5 | using System.Text.Json;
6 | using System.Threading.Tasks;
7 |
8 | namespace TheConsole
9 | {
10 | class Program
11 | {
12 | static void Main(string[] args)
13 | {
14 |
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Video 1 - GET/Begin/TheConsole/TheConsole.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/ApplicationDbContext.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.EntityFrameworkCore;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Diagnostics.CodeAnalysis;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace API
10 | {
11 | public class ApplicationDbContext : DbContext
12 | {
13 | public ApplicationDbContext([NotNull] DbContextOptions options) : base(options)
14 | {
15 | }
16 |
17 | public DbSet People { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/Controllers/PeopleController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Mvc;
3 | using Microsoft.EntityFrameworkCore;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace API.Controllers
10 | {
11 | [ApiController]
12 | [Route("api/people")]
13 | public class PeopleController: ControllerBase
14 | {
15 | private readonly ApplicationDbContext context;
16 |
17 | public PeopleController(ApplicationDbContext context)
18 | {
19 | this.context = context;
20 | }
21 |
22 | [HttpGet]
23 | public async Task>> Get()
24 | {
25 | return NotFound();
26 | return new List() { new Person() { Id = 1, Name = "Felipe"},
27 | new Person(){Id = 2, Name = "Claudia"}};
28 | //return await context.People.ToListAsync();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 |
8 | namespace API.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get()
28 | {
29 | var rng = new Random();
30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast
31 | {
32 | Date = DateTime.Now.AddDays(index),
33 | TemperatureC = rng.Next(-20, 55),
34 | Summary = Summaries[rng.Next(Summaries.Length)]
35 | })
36 | .ToArray();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Hosting;
2 | using Microsoft.Extensions.Configuration;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Logging;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace API
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:58393",
8 | "sslPort": 44337
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "API": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Builder;
2 | using Microsoft.AspNetCore.Hosting;
3 | using Microsoft.AspNetCore.HttpsPolicy;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.EntityFrameworkCore;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.DependencyInjection;
8 | using Microsoft.Extensions.Hosting;
9 | using Microsoft.Extensions.Logging;
10 | using Microsoft.OpenApi.Models;
11 | using System;
12 | using System.Collections.Generic;
13 | using System.Linq;
14 | using System.Threading.Tasks;
15 |
16 | namespace API
17 | {
18 | public class Startup
19 | {
20 | public Startup(IConfiguration configuration)
21 | {
22 | Configuration = configuration;
23 | }
24 |
25 | public IConfiguration Configuration { get; }
26 |
27 | // This method gets called by the runtime. Use this method to add services to the container.
28 | public void ConfigureServices(IServiceCollection services)
29 | {
30 | services.AddDbContext(options => options.UseInMemoryDatabase("mydatabase"));
31 | services.AddControllers();
32 | services.AddSwaggerGen(c =>
33 | {
34 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
35 | });
36 | }
37 |
38 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
39 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
40 | {
41 | if (env.IsDevelopment())
42 | {
43 | app.UseDeveloperExceptionPage();
44 | app.UseSwagger();
45 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
46 | }
47 |
48 | app.UseHttpsRedirection();
49 |
50 | app.UseRouting();
51 |
52 | app.UseAuthorization();
53 |
54 | app.UseEndpoints(endpoints =>
55 | {
56 | endpoints.MapControllers();
57 | });
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace API
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/Common/Person.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Common
4 | {
5 | public class Person
6 | {
7 | public int Id { get; set; }
8 | public string Name { get; set; }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/HttpClientTutorial.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30804.86
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheConsole", "TheConsole\TheConsole.csproj", "{3555DFEA-3E28-4519-95E3-5DA41622D4FF}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{D62139AC-C84A-4086-A4E2-EC9845A95CAF}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{058D1032-8480-4581-B6E3-EA7B704E233E}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {1A7A7613-556B-4F6B-8684-057AD8B535C0}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/TheConsole/Program.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net.Http;
5 | using System.Text.Json;
6 | using System.Threading.Tasks;
7 |
8 | namespace TheConsole
9 | {
10 | class Program
11 | {
12 | static async Task Main(string[] args)
13 | {
14 | var url = "https://localhost:5001/api/people";
15 |
16 | using (var httpClient = new HttpClient())
17 | {
18 | using var response = await httpClient.GetAsync(url);
19 |
20 | var responseString2 = await httpClient.GetStringAsync(url);
21 |
22 | //if (response.StatusCode == System.Net.HttpStatusCode.OK)
23 | //{
24 | // var responseString = await response.Content.ReadAsStringAsync();
25 | // var people = JsonSerializer.Deserialize>(responseString,
26 | // new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
27 | //}
28 | //else if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
29 | //{
30 |
31 | //}
32 |
33 | switch (response.StatusCode)
34 | {
35 | case System.Net.HttpStatusCode.Continue:
36 | break;
37 | case System.Net.HttpStatusCode.SwitchingProtocols:
38 | break;
39 | case System.Net.HttpStatusCode.Processing:
40 | break;
41 | case System.Net.HttpStatusCode.EarlyHints:
42 | break;
43 | case System.Net.HttpStatusCode.OK:
44 | var responseString = await response.Content.ReadAsStringAsync();
45 | var people = JsonSerializer.Deserialize>(responseString,
46 | new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
47 | break;
48 | case System.Net.HttpStatusCode.Created:
49 | break;
50 | case System.Net.HttpStatusCode.Accepted:
51 | break;
52 | case System.Net.HttpStatusCode.NonAuthoritativeInformation:
53 | break;
54 | case System.Net.HttpStatusCode.NoContent:
55 | break;
56 | case System.Net.HttpStatusCode.ResetContent:
57 | break;
58 | case System.Net.HttpStatusCode.PartialContent:
59 | break;
60 | case System.Net.HttpStatusCode.MultiStatus:
61 | break;
62 | case System.Net.HttpStatusCode.AlreadyReported:
63 | break;
64 | case System.Net.HttpStatusCode.IMUsed:
65 | break;
66 | case System.Net.HttpStatusCode.Ambiguous:
67 | break;
68 | case System.Net.HttpStatusCode.Moved:
69 | break;
70 | case System.Net.HttpStatusCode.Found:
71 | break;
72 | case System.Net.HttpStatusCode.RedirectMethod:
73 | break;
74 | case System.Net.HttpStatusCode.NotModified:
75 | break;
76 | case System.Net.HttpStatusCode.UseProxy:
77 | break;
78 | case System.Net.HttpStatusCode.Unused:
79 | break;
80 | case System.Net.HttpStatusCode.RedirectKeepVerb:
81 | break;
82 | case System.Net.HttpStatusCode.PermanentRedirect:
83 | break;
84 | case System.Net.HttpStatusCode.BadRequest:
85 | break;
86 | case System.Net.HttpStatusCode.Unauthorized:
87 | break;
88 | case System.Net.HttpStatusCode.PaymentRequired:
89 | break;
90 | case System.Net.HttpStatusCode.Forbidden:
91 | break;
92 | case System.Net.HttpStatusCode.NotFound:
93 | break;
94 | case System.Net.HttpStatusCode.MethodNotAllowed:
95 | break;
96 | case System.Net.HttpStatusCode.NotAcceptable:
97 | break;
98 | case System.Net.HttpStatusCode.ProxyAuthenticationRequired:
99 | break;
100 | case System.Net.HttpStatusCode.RequestTimeout:
101 | break;
102 | case System.Net.HttpStatusCode.Conflict:
103 | break;
104 | case System.Net.HttpStatusCode.Gone:
105 | break;
106 | case System.Net.HttpStatusCode.LengthRequired:
107 | break;
108 | case System.Net.HttpStatusCode.PreconditionFailed:
109 | break;
110 | case System.Net.HttpStatusCode.RequestEntityTooLarge:
111 | break;
112 | case System.Net.HttpStatusCode.RequestUriTooLong:
113 | break;
114 | case System.Net.HttpStatusCode.UnsupportedMediaType:
115 | break;
116 | case System.Net.HttpStatusCode.RequestedRangeNotSatisfiable:
117 | break;
118 | case System.Net.HttpStatusCode.ExpectationFailed:
119 | break;
120 | case System.Net.HttpStatusCode.MisdirectedRequest:
121 | break;
122 | case System.Net.HttpStatusCode.UnprocessableEntity:
123 | break;
124 | case System.Net.HttpStatusCode.Locked:
125 | break;
126 | case System.Net.HttpStatusCode.FailedDependency:
127 | break;
128 | case System.Net.HttpStatusCode.UpgradeRequired:
129 | break;
130 | case System.Net.HttpStatusCode.PreconditionRequired:
131 | break;
132 | case System.Net.HttpStatusCode.TooManyRequests:
133 | break;
134 | case System.Net.HttpStatusCode.RequestHeaderFieldsTooLarge:
135 | break;
136 | case System.Net.HttpStatusCode.UnavailableForLegalReasons:
137 | break;
138 | case System.Net.HttpStatusCode.InternalServerError:
139 | break;
140 | case System.Net.HttpStatusCode.NotImplemented:
141 | break;
142 | case System.Net.HttpStatusCode.BadGateway:
143 | break;
144 | case System.Net.HttpStatusCode.ServiceUnavailable:
145 | break;
146 | case System.Net.HttpStatusCode.GatewayTimeout:
147 | break;
148 | case System.Net.HttpStatusCode.HttpVersionNotSupported:
149 | break;
150 | case System.Net.HttpStatusCode.VariantAlsoNegotiates:
151 | break;
152 | case System.Net.HttpStatusCode.InsufficientStorage:
153 | break;
154 | case System.Net.HttpStatusCode.LoopDetected:
155 | break;
156 | case System.Net.HttpStatusCode.NotExtended:
157 | break;
158 | case System.Net.HttpStatusCode.NetworkAuthenticationRequired:
159 | break;
160 | default:
161 | break;
162 | }
163 |
164 |
165 | }
166 | }
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/Video 1 - GET/End/TheConsole/TheConsole.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/ApplicationDbContext.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.EntityFrameworkCore;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Diagnostics.CodeAnalysis;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace API
10 | {
11 | public class ApplicationDbContext : DbContext
12 | {
13 | public ApplicationDbContext([NotNull] DbContextOptions options) : base(options)
14 | {
15 | }
16 |
17 | public DbSet People { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/Controllers/PeopleController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Mvc;
3 | using Microsoft.EntityFrameworkCore;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace API.Controllers
10 | {
11 | [ApiController]
12 | [Route("api/people")]
13 | public class PeopleController: ControllerBase
14 | {
15 | private readonly ApplicationDbContext context;
16 |
17 | public PeopleController(ApplicationDbContext context)
18 | {
19 | this.context = context;
20 | }
21 |
22 | [HttpGet]
23 | public async Task>> Get()
24 | {
25 | return NotFound();
26 | return new List() { new Person() { Id = 1, Name = "Felipe"},
27 | new Person(){Id = 2, Name = "Claudia"}};
28 | //return await context.People.ToListAsync();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 |
8 | namespace API.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get()
28 | {
29 | var rng = new Random();
30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast
31 | {
32 | Date = DateTime.Now.AddDays(index),
33 | TemperatureC = rng.Next(-20, 55),
34 | Summary = Summaries[rng.Next(Summaries.Length)]
35 | })
36 | .ToArray();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Hosting;
2 | using Microsoft.Extensions.Configuration;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Logging;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace API
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:58393",
8 | "sslPort": 44337
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "API": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Builder;
2 | using Microsoft.AspNetCore.Hosting;
3 | using Microsoft.AspNetCore.HttpsPolicy;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.EntityFrameworkCore;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.DependencyInjection;
8 | using Microsoft.Extensions.Hosting;
9 | using Microsoft.Extensions.Logging;
10 | using Microsoft.OpenApi.Models;
11 | using System;
12 | using System.Collections.Generic;
13 | using System.Linq;
14 | using System.Threading.Tasks;
15 |
16 | namespace API
17 | {
18 | public class Startup
19 | {
20 | public Startup(IConfiguration configuration)
21 | {
22 | Configuration = configuration;
23 | }
24 |
25 | public IConfiguration Configuration { get; }
26 |
27 | // This method gets called by the runtime. Use this method to add services to the container.
28 | public void ConfigureServices(IServiceCollection services)
29 | {
30 | services.AddDbContext(options => options.UseInMemoryDatabase("mydatabase"));
31 | services.AddControllers();
32 | services.AddSwaggerGen(c =>
33 | {
34 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
35 | });
36 | }
37 |
38 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
39 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
40 | {
41 | if (env.IsDevelopment())
42 | {
43 | app.UseDeveloperExceptionPage();
44 | app.UseSwagger();
45 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
46 | }
47 |
48 | app.UseHttpsRedirection();
49 |
50 | app.UseRouting();
51 |
52 | app.UseAuthorization();
53 |
54 | app.UseEndpoints(endpoints =>
55 | {
56 | endpoints.MapControllers();
57 | });
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace API
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/Common/Person.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Common
4 | {
5 | public class Person
6 | {
7 | public int Id { get; set; }
8 | public string Name { get; set; }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/HttpClientTutorial.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30804.86
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheConsole", "TheConsole\TheConsole.csproj", "{3555DFEA-3E28-4519-95E3-5DA41622D4FF}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{D62139AC-C84A-4086-A4E2-EC9845A95CAF}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{058D1032-8480-4581-B6E3-EA7B704E233E}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {1A7A7613-556B-4F6B-8684-057AD8B535C0}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/TheConsole/Program.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net.Http;
5 | using System.Text.Json;
6 | using System.Threading.Tasks;
7 |
8 | namespace TheConsole
9 | {
10 | class Program
11 | {
12 | static async Task Main(string[] args)
13 | {
14 | var url = "https://localhost:5001/api/people";
15 |
16 | using (var httpClient = new HttpClient())
17 | {
18 | using var response = await httpClient.GetAsync(url);
19 |
20 | var responseString2 = await httpClient.GetStringAsync(url);
21 |
22 | //if (response.StatusCode == System.Net.HttpStatusCode.OK)
23 | //{
24 | // var responseString = await response.Content.ReadAsStringAsync();
25 | // var people = JsonSerializer.Deserialize>(responseString,
26 | // new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
27 | //}
28 | //else if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
29 | //{
30 |
31 | //}
32 |
33 | switch (response.StatusCode)
34 | {
35 | case System.Net.HttpStatusCode.Continue:
36 | break;
37 | case System.Net.HttpStatusCode.SwitchingProtocols:
38 | break;
39 | case System.Net.HttpStatusCode.Processing:
40 | break;
41 | case System.Net.HttpStatusCode.EarlyHints:
42 | break;
43 | case System.Net.HttpStatusCode.OK:
44 | var responseString = await response.Content.ReadAsStringAsync();
45 | var people = JsonSerializer.Deserialize>(responseString,
46 | new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
47 | break;
48 | case System.Net.HttpStatusCode.Created:
49 | break;
50 | case System.Net.HttpStatusCode.Accepted:
51 | break;
52 | case System.Net.HttpStatusCode.NonAuthoritativeInformation:
53 | break;
54 | case System.Net.HttpStatusCode.NoContent:
55 | break;
56 | case System.Net.HttpStatusCode.ResetContent:
57 | break;
58 | case System.Net.HttpStatusCode.PartialContent:
59 | break;
60 | case System.Net.HttpStatusCode.MultiStatus:
61 | break;
62 | case System.Net.HttpStatusCode.AlreadyReported:
63 | break;
64 | case System.Net.HttpStatusCode.IMUsed:
65 | break;
66 | case System.Net.HttpStatusCode.Ambiguous:
67 | break;
68 | case System.Net.HttpStatusCode.Moved:
69 | break;
70 | case System.Net.HttpStatusCode.Found:
71 | break;
72 | case System.Net.HttpStatusCode.RedirectMethod:
73 | break;
74 | case System.Net.HttpStatusCode.NotModified:
75 | break;
76 | case System.Net.HttpStatusCode.UseProxy:
77 | break;
78 | case System.Net.HttpStatusCode.Unused:
79 | break;
80 | case System.Net.HttpStatusCode.RedirectKeepVerb:
81 | break;
82 | case System.Net.HttpStatusCode.PermanentRedirect:
83 | break;
84 | case System.Net.HttpStatusCode.BadRequest:
85 | break;
86 | case System.Net.HttpStatusCode.Unauthorized:
87 | break;
88 | case System.Net.HttpStatusCode.PaymentRequired:
89 | break;
90 | case System.Net.HttpStatusCode.Forbidden:
91 | break;
92 | case System.Net.HttpStatusCode.NotFound:
93 | break;
94 | case System.Net.HttpStatusCode.MethodNotAllowed:
95 | break;
96 | case System.Net.HttpStatusCode.NotAcceptable:
97 | break;
98 | case System.Net.HttpStatusCode.ProxyAuthenticationRequired:
99 | break;
100 | case System.Net.HttpStatusCode.RequestTimeout:
101 | break;
102 | case System.Net.HttpStatusCode.Conflict:
103 | break;
104 | case System.Net.HttpStatusCode.Gone:
105 | break;
106 | case System.Net.HttpStatusCode.LengthRequired:
107 | break;
108 | case System.Net.HttpStatusCode.PreconditionFailed:
109 | break;
110 | case System.Net.HttpStatusCode.RequestEntityTooLarge:
111 | break;
112 | case System.Net.HttpStatusCode.RequestUriTooLong:
113 | break;
114 | case System.Net.HttpStatusCode.UnsupportedMediaType:
115 | break;
116 | case System.Net.HttpStatusCode.RequestedRangeNotSatisfiable:
117 | break;
118 | case System.Net.HttpStatusCode.ExpectationFailed:
119 | break;
120 | case System.Net.HttpStatusCode.MisdirectedRequest:
121 | break;
122 | case System.Net.HttpStatusCode.UnprocessableEntity:
123 | break;
124 | case System.Net.HttpStatusCode.Locked:
125 | break;
126 | case System.Net.HttpStatusCode.FailedDependency:
127 | break;
128 | case System.Net.HttpStatusCode.UpgradeRequired:
129 | break;
130 | case System.Net.HttpStatusCode.PreconditionRequired:
131 | break;
132 | case System.Net.HttpStatusCode.TooManyRequests:
133 | break;
134 | case System.Net.HttpStatusCode.RequestHeaderFieldsTooLarge:
135 | break;
136 | case System.Net.HttpStatusCode.UnavailableForLegalReasons:
137 | break;
138 | case System.Net.HttpStatusCode.InternalServerError:
139 | break;
140 | case System.Net.HttpStatusCode.NotImplemented:
141 | break;
142 | case System.Net.HttpStatusCode.BadGateway:
143 | break;
144 | case System.Net.HttpStatusCode.ServiceUnavailable:
145 | break;
146 | case System.Net.HttpStatusCode.GatewayTimeout:
147 | break;
148 | case System.Net.HttpStatusCode.HttpVersionNotSupported:
149 | break;
150 | case System.Net.HttpStatusCode.VariantAlsoNegotiates:
151 | break;
152 | case System.Net.HttpStatusCode.InsufficientStorage:
153 | break;
154 | case System.Net.HttpStatusCode.LoopDetected:
155 | break;
156 | case System.Net.HttpStatusCode.NotExtended:
157 | break;
158 | case System.Net.HttpStatusCode.NetworkAuthenticationRequired:
159 | break;
160 | default:
161 | break;
162 | }
163 |
164 |
165 | }
166 | }
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/Video 2 - POST/Begin/TheConsole/TheConsole.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/ApplicationDbContext.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.EntityFrameworkCore;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Diagnostics.CodeAnalysis;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace API
10 | {
11 | public class ApplicationDbContext : DbContext
12 | {
13 | public ApplicationDbContext([NotNull] DbContextOptions options) : base(options)
14 | {
15 | }
16 |
17 | public DbSet People { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/Controllers/PeopleController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Mvc;
3 | using Microsoft.EntityFrameworkCore;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace API.Controllers
10 | {
11 | [ApiController]
12 | [Route("api/people")]
13 | public class PeopleController: ControllerBase
14 | {
15 | private readonly ApplicationDbContext context;
16 |
17 | public PeopleController(ApplicationDbContext context)
18 | {
19 | this.context = context;
20 | }
21 |
22 | [HttpGet]
23 | public async Task>> Get()
24 | {
25 | return await context.People.ToListAsync();
26 | }
27 |
28 | [HttpPost]
29 | public async Task> Post(Person person)
30 | {
31 | context.Add(person);
32 | await context.SaveChangesAsync();
33 | return person.Id;
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 |
8 | namespace API.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get()
28 | {
29 | var rng = new Random();
30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast
31 | {
32 | Date = DateTime.Now.AddDays(index),
33 | TemperatureC = rng.Next(-20, 55),
34 | Summary = Summaries[rng.Next(Summaries.Length)]
35 | })
36 | .ToArray();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Hosting;
2 | using Microsoft.Extensions.Configuration;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Logging;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace API
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:58393",
8 | "sslPort": 44337
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "API": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Builder;
2 | using Microsoft.AspNetCore.Hosting;
3 | using Microsoft.AspNetCore.HttpsPolicy;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.EntityFrameworkCore;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.DependencyInjection;
8 | using Microsoft.Extensions.Hosting;
9 | using Microsoft.Extensions.Logging;
10 | using Microsoft.OpenApi.Models;
11 | using System;
12 | using System.Collections.Generic;
13 | using System.Linq;
14 | using System.Threading.Tasks;
15 |
16 | namespace API
17 | {
18 | public class Startup
19 | {
20 | public Startup(IConfiguration configuration)
21 | {
22 | Configuration = configuration;
23 | }
24 |
25 | public IConfiguration Configuration { get; }
26 |
27 | // This method gets called by the runtime. Use this method to add services to the container.
28 | public void ConfigureServices(IServiceCollection services)
29 | {
30 | services.AddDbContext(options => options.UseInMemoryDatabase("mydatabase"));
31 | services.AddControllers();
32 | services.AddSwaggerGen(c =>
33 | {
34 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
35 | });
36 | }
37 |
38 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
39 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
40 | {
41 | if (env.IsDevelopment())
42 | {
43 | app.UseDeveloperExceptionPage();
44 | app.UseSwagger();
45 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
46 | }
47 |
48 | app.UseHttpsRedirection();
49 |
50 | app.UseRouting();
51 |
52 | app.UseAuthorization();
53 |
54 | app.UseEndpoints(endpoints =>
55 | {
56 | endpoints.MapControllers();
57 | });
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace API
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/Common/Person.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel.DataAnnotations;
3 |
4 | namespace Common
5 | {
6 | public class Person
7 | {
8 | public int Id { get; set; }
9 | [Required]
10 | public string Name { get; set; }
11 | [Range(0, 120)]
12 | public int Age { get; set; }
13 | [EmailAddress]
14 | public string Email { get; set; }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/HttpClientTutorial.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30804.86
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheConsole", "TheConsole\TheConsole.csproj", "{3555DFEA-3E28-4519-95E3-5DA41622D4FF}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{D62139AC-C84A-4086-A4E2-EC9845A95CAF}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{058D1032-8480-4581-B6E3-EA7B704E233E}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {1A7A7613-556B-4F6B-8684-057AD8B535C0}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/TheConsole/Program.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net.Http;
5 | using System.Net.Http.Json;
6 | using System.Text;
7 | using System.Text.Json;
8 | using System.Threading.Tasks;
9 |
10 | namespace TheConsole
11 | {
12 | class Program
13 | {
14 | static async Task Main(string[] args)
15 | {
16 | var url = "https://localhost:5001/api/people";
17 | var jsonSerializerOptions = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
18 |
19 | using (var httpClient = new HttpClient())
20 | {
21 | // Example 1: PostAsJsonAsync
22 | //var newPerson = new Person() { Name = "Felipe" };
23 | //var response = await httpClient.PostAsJsonAsync(url, newPerson);
24 | //if (response.IsSuccessStatusCode)
25 | //{
26 | // var id = await response.Content.ReadAsStringAsync();
27 | // Console.WriteLine("The id is " + id);
28 | //}
29 |
30 | // Example 2: PostAsync
31 | //var newPerson2 = new Person() { Name = "Claudia" };
32 | //var newPerson2Serialized = JsonSerializer.Serialize(newPerson2);
33 | //var stringContent = new StringContent(newPerson2Serialized, Encoding.UTF8, "application/json");
34 |
35 | //var response = await httpClient.PostAsync(url, stringContent);
36 |
37 | // Example 3: Validations
38 | var newPerson3 = new Person() { Age = -1, Email = "abc" };
39 | var response = await httpClient.PostAsJsonAsync(url, newPerson3);
40 |
41 | if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
42 | {
43 | var body = await response.Content.ReadAsStringAsync();
44 | var errorsFromWebAPI = Utils.ExtractErrorsFromWebAPIResponse(body);
45 |
46 | foreach (var fieldWithErrors in errorsFromWebAPI)
47 | {
48 | Console.WriteLine($"-{fieldWithErrors.Key}");
49 | foreach (var error in fieldWithErrors.Value)
50 | {
51 | Console.WriteLine($" {error}");
52 | }
53 | }
54 | }
55 |
56 | var people = JsonSerializer.Deserialize>(await httpClient.GetStringAsync(url),
57 | jsonSerializerOptions);
58 | }
59 |
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/TheConsole/TheConsole.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Video 2 - POST/End/TheConsole/Utils.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Text.Json;
6 | using System.Threading.Tasks;
7 |
8 | namespace TheConsole
9 | {
10 | public class Utils
11 | {
12 | public static Dictionary> ExtractErrorsFromWebAPIResponse(string body)
13 | {
14 | var response = new Dictionary>();
15 |
16 | var jsonElement = JsonSerializer.Deserialize(body);
17 | var errorsJsonElement = jsonElement.GetProperty("errors");
18 | foreach (var fieldWithErrors in errorsJsonElement.EnumerateObject())
19 | {
20 | var field = fieldWithErrors.Name;
21 | var errors = new List();
22 | foreach (var errorKind in fieldWithErrors.Value.EnumerateArray())
23 | {
24 | var error = errorKind.GetString();
25 | errors.Add(error);
26 | }
27 | response.Add(field, errors);
28 | }
29 |
30 | return response;
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/ApplicationDbContext.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
3 | using Microsoft.EntityFrameworkCore;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Diagnostics.CodeAnalysis;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace API
11 | {
12 | public class ApplicationDbContext : IdentityDbContext
13 | {
14 | public ApplicationDbContext([NotNull] DbContextOptions options) : base(options)
15 | {
16 | }
17 |
18 | public DbSet People { get; set; }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/Controllers/AccountsController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Identity;
3 | using Microsoft.AspNetCore.Mvc;
4 | using Microsoft.Extensions.Configuration;
5 | using Microsoft.IdentityModel.Tokens;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.IdentityModel.Tokens.Jwt;
9 | using System.Linq;
10 | using System.Security.Claims;
11 | using System.Text;
12 | using System.Threading.Tasks;
13 |
14 | namespace API.Controllers
15 | {
16 | [ApiController]
17 | [Route("api/accounts")]
18 | public class AccountsController: ControllerBase
19 | {
20 | private readonly UserManager _userManager;
21 | private readonly SignInManager _signInManager;
22 | private readonly IConfiguration _configuration;
23 | private readonly ApplicationDbContext context;
24 |
25 | public AccountsController(
26 | UserManager userManager,
27 | SignInManager signInManager,
28 | IConfiguration configuration)
29 | {
30 | _userManager = userManager;
31 | _signInManager = signInManager;
32 | _configuration = configuration;
33 | }
34 |
35 | [HttpPost("Create")]
36 | public async Task> CreateUser([FromBody] UserInfo model)
37 | {
38 | var user = new IdentityUser { UserName = model.EmailAddress, Email = model.EmailAddress };
39 | var result = await _userManager.CreateAsync(user, model.Password);
40 |
41 | if (result.Succeeded)
42 | {
43 | return await BuildToken(model);
44 | }
45 | else
46 | {
47 | return BadRequest(result.Errors);
48 | }
49 | }
50 |
51 | [HttpPost("Login")]
52 | public async Task> Login([FromBody] UserInfo model)
53 | {
54 | var result = await _signInManager.PasswordSignInAsync(model.EmailAddress,
55 | model.Password, isPersistent: false, lockoutOnFailure: false);
56 |
57 | if (result.Succeeded)
58 | {
59 | return await BuildToken(model);
60 | }
61 | else
62 | {
63 | return BadRequest("Invalid login attempt");
64 | }
65 | }
66 |
67 |
68 | private async Task BuildToken(UserInfo userInfo)
69 | {
70 | var claims = new List()
71 | {
72 | new Claim(ClaimTypes.Name, userInfo.EmailAddress),
73 | new Claim(ClaimTypes.Email, userInfo.EmailAddress),
74 | };
75 |
76 | var identityUser = await _userManager.FindByEmailAsync(userInfo.EmailAddress);
77 | var claimsDB = await _userManager.GetClaimsAsync(identityUser);
78 |
79 | claims.AddRange(claimsDB);
80 |
81 | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWTkey"]));
82 | var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
83 |
84 | var expiration = DateTime.UtcNow.AddYears(1);
85 |
86 | JwtSecurityToken token = new JwtSecurityToken(
87 | issuer: null,
88 | audience: null,
89 | claims: claims,
90 | expires: expiration,
91 | signingCredentials: creds);
92 |
93 | return new UserToken()
94 | {
95 | Token = new JwtSecurityTokenHandler().WriteToken(token),
96 | Expiration = expiration
97 | };
98 |
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/Controllers/PeopleController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Authentication.JwtBearer;
3 | using Microsoft.AspNetCore.Authorization;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.EntityFrameworkCore;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Threading.Tasks;
10 |
11 | namespace API.Controllers
12 | {
13 | [ApiController]
14 | [Route("api/people")]
15 | public class PeopleController: ControllerBase
16 | {
17 | private readonly ApplicationDbContext context;
18 |
19 | public PeopleController(ApplicationDbContext context)
20 | {
21 | this.context = context;
22 | }
23 |
24 | [HttpGet]
25 | public async Task>> Get()
26 | {
27 | return await context.People.ToListAsync();
28 | }
29 |
30 | [HttpPost]
31 | [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
32 | public async Task> Post(Person person)
33 | {
34 | context.Add(person);
35 | await context.SaveChangesAsync();
36 | return person.Id;
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 |
8 | namespace API.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get([FromHeader] int weatherAmount = 5)
28 | {
29 |
30 | // Note: another way of getting a header from the request
31 | //var weatherAmount2 = int.Parse(HttpContext.Request.Headers["weatherAmount"].ToString());
32 |
33 | var rng = new Random();
34 | return Enumerable.Range(1, weatherAmount).Select(index => new WeatherForecast
35 | {
36 | Date = DateTime.Now.AddDays(index),
37 | TemperatureC = rng.Next(-20, 55),
38 | Summary = Summaries[rng.Next(Summaries.Length)]
39 | })
40 | .ToArray();
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Hosting;
2 | using Microsoft.Extensions.Configuration;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Logging;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace API
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:58393",
8 | "sslPort": 44337
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "API": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.JwtBearer;
2 | using Microsoft.AspNetCore.Builder;
3 | using Microsoft.AspNetCore.Hosting;
4 | using Microsoft.AspNetCore.HttpsPolicy;
5 | using Microsoft.AspNetCore.Identity;
6 | using Microsoft.AspNetCore.Mvc;
7 | using Microsoft.EntityFrameworkCore;
8 | using Microsoft.Extensions.Configuration;
9 | using Microsoft.Extensions.DependencyInjection;
10 | using Microsoft.Extensions.Hosting;
11 | using Microsoft.Extensions.Logging;
12 | using Microsoft.IdentityModel.Tokens;
13 | using Microsoft.OpenApi.Models;
14 | using System;
15 | using System.Collections.Generic;
16 | using System.Linq;
17 | using System.Text;
18 | using System.Threading.Tasks;
19 |
20 | namespace API
21 | {
22 | public class Startup
23 | {
24 | public Startup(IConfiguration configuration)
25 | {
26 | Configuration = configuration;
27 | }
28 |
29 | public IConfiguration Configuration { get; }
30 |
31 | // This method gets called by the runtime. Use this method to add services to the container.
32 | public void ConfigureServices(IServiceCollection services)
33 | {
34 | services.AddDbContext(options => options.UseInMemoryDatabase("mydatabase"));
35 | services.AddControllers();
36 | services.AddSwaggerGen(c =>
37 | {
38 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
39 | });
40 |
41 | services.AddIdentity()
42 | .AddEntityFrameworkStores()
43 | .AddDefaultTokenProviders();
44 |
45 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
46 | .AddJwtBearer(options =>
47 | options.TokenValidationParameters = new TokenValidationParameters
48 | {
49 | ValidateIssuer = false,
50 | ValidateAudience = false,
51 | ValidateLifetime = true,
52 | ValidateIssuerSigningKey = true,
53 | IssuerSigningKey = new SymmetricSecurityKey(
54 | Encoding.UTF8.GetBytes(Configuration["jwtkey"])),
55 | ClockSkew = TimeSpan.Zero
56 | }
57 | );
58 |
59 | }
60 |
61 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
62 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
63 | {
64 | if (env.IsDevelopment())
65 | {
66 | app.UseDeveloperExceptionPage();
67 | app.UseSwagger();
68 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
69 | }
70 |
71 | app.UseHttpsRedirection();
72 |
73 | app.UseRouting();
74 |
75 | app.UseAuthorization();
76 |
77 | app.UseEndpoints(endpoints =>
78 | {
79 | endpoints.MapControllers();
80 | });
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace API
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "JWTkey": "ASKMDLAMSLK3MLK3M4LK23M4LK23MLKMLFKDSMDFLKSDMFLKM33SDS",
3 | "Logging": {
4 | "LogLevel": {
5 | "Default": "Information",
6 | "Microsoft": "Warning",
7 | "Microsoft.Hosting.Lifetime": "Information"
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/Common/Person.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel.DataAnnotations;
3 |
4 | namespace Common
5 | {
6 | public class Person
7 | {
8 | public int Id { get; set; }
9 | [Required]
10 | public string Name { get; set; }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/Common/UserInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel.DataAnnotations;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace Common
9 | {
10 | public class UserInfo
11 | {
12 | [Required]
13 | [EmailAddress]
14 | public string EmailAddress { get; set; }
15 | [Required]
16 | public string Password { get; set; }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/Common/UserToken.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace Common
8 | {
9 | public class UserToken
10 | {
11 | public string Token { get; set; }
12 | public DateTime Expiration { get; set; }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/Common/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Common
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/HttpClientTutorial.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30804.86
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheConsole", "TheConsole\TheConsole.csproj", "{3555DFEA-3E28-4519-95E3-5DA41622D4FF}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{D62139AC-C84A-4086-A4E2-EC9845A95CAF}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{058D1032-8480-4581-B6E3-EA7B704E233E}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {1A7A7613-556B-4F6B-8684-057AD8B535C0}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/TheConsole/Program.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net;
5 | using System.Net.Http;
6 | using System.Net.Http.Headers;
7 | using System.Net.Http.Json;
8 | using System.Text;
9 | using System.Text.Json;
10 | using System.Threading.Tasks;
11 |
12 | namespace TheConsole
13 | {
14 | class Program
15 | {
16 | static string urlAccounts = "https://localhost:5001/api/accounts";
17 | static UserInfo credentials = new UserInfo() { EmailAddress = "felipe@hotmail.com", Password = "aA123456!" };
18 | static async Task Main(string[] args)
19 | {
20 | var urlPeople = "https://localhost:5001/api/people";
21 | var jsonSerializerOptions = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
22 | var urlExample1 = "https://localhost:5001/WeatherForecast";
23 |
24 | using (var httpClient = new HttpClient())
25 | {
26 | //example 1: Sending a value on the header once
27 | //Ideal when we don't want to affect other HTTP requests
28 |
29 | // example 2: Modifying the headers of all of the requests
30 |
31 | //example 3: JWT
32 |
33 | }
34 |
35 | }
36 |
37 | private async static Task CreateUser()
38 | {
39 | try
40 | {
41 | using (var httpClient = new HttpClient())
42 | {
43 | var respuesta = await httpClient.PostAsJsonAsync($"{urlAccounts}/create", credentials);
44 | if (respuesta.StatusCode == HttpStatusCode.InternalServerError)
45 | {
46 | respuesta.EnsureSuccessStatusCode();
47 | }
48 | }
49 | }
50 | catch (Exception e)
51 | {
52 | Console.WriteLine(e);
53 | }
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/TheConsole/TheConsole.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/Begin/TheConsole/Utils.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Text.Json;
6 | using System.Threading.Tasks;
7 |
8 | namespace TheConsole
9 | {
10 | public class Utils
11 | {
12 | public static Dictionary> ExtractErrorsFromWebAPIResponse(string body)
13 | {
14 | var response = new Dictionary>();
15 |
16 | var jsonElement = JsonSerializer.Deserialize(body);
17 | var errorsJsonElement = jsonElement.GetProperty("errors");
18 | foreach (var fieldWithErrors in errorsJsonElement.EnumerateObject())
19 | {
20 | var field = fieldWithErrors.Name;
21 | var errors = new List();
22 | foreach (var errorKind in fieldWithErrors.Value.EnumerateArray())
23 | {
24 | var error = errorKind.GetString();
25 | errors.Add(error);
26 | }
27 | response.Add(field, errors);
28 | }
29 |
30 | return response;
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/ApplicationDbContext.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
3 | using Microsoft.EntityFrameworkCore;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Diagnostics.CodeAnalysis;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace API
11 | {
12 | public class ApplicationDbContext : IdentityDbContext
13 | {
14 | public ApplicationDbContext([NotNull] DbContextOptions options) : base(options)
15 | {
16 | }
17 |
18 | public DbSet People { get; set; }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/Controllers/AccountsController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Identity;
3 | using Microsoft.AspNetCore.Mvc;
4 | using Microsoft.Extensions.Configuration;
5 | using Microsoft.IdentityModel.Tokens;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.IdentityModel.Tokens.Jwt;
9 | using System.Linq;
10 | using System.Security.Claims;
11 | using System.Text;
12 | using System.Threading.Tasks;
13 |
14 | namespace API.Controllers
15 | {
16 | [ApiController]
17 | [Route("api/accounts")]
18 | public class AccountsController: ControllerBase
19 | {
20 | private readonly UserManager _userManager;
21 | private readonly SignInManager _signInManager;
22 | private readonly IConfiguration _configuration;
23 | private readonly ApplicationDbContext context;
24 |
25 | public AccountsController(
26 | UserManager userManager,
27 | SignInManager signInManager,
28 | IConfiguration configuration)
29 | {
30 | _userManager = userManager;
31 | _signInManager = signInManager;
32 | _configuration = configuration;
33 | }
34 |
35 | [HttpPost("Create")]
36 | public async Task> CreateUser([FromBody] UserInfo model)
37 | {
38 | var user = new IdentityUser { UserName = model.EmailAddress, Email = model.EmailAddress };
39 | var result = await _userManager.CreateAsync(user, model.Password);
40 |
41 | if (result.Succeeded)
42 | {
43 | return await BuildToken(model);
44 | }
45 | else
46 | {
47 | return BadRequest(result.Errors);
48 | }
49 | }
50 |
51 | [HttpPost("Login")]
52 | public async Task> Login([FromBody] UserInfo model)
53 | {
54 | var result = await _signInManager.PasswordSignInAsync(model.EmailAddress,
55 | model.Password, isPersistent: false, lockoutOnFailure: false);
56 |
57 | if (result.Succeeded)
58 | {
59 | return await BuildToken(model);
60 | }
61 | else
62 | {
63 | return BadRequest("Invalid login attempt");
64 | }
65 | }
66 |
67 |
68 | private async Task BuildToken(UserInfo userInfo)
69 | {
70 | var claims = new List()
71 | {
72 | new Claim(ClaimTypes.Name, userInfo.EmailAddress),
73 | new Claim(ClaimTypes.Email, userInfo.EmailAddress),
74 | };
75 |
76 | var identityUser = await _userManager.FindByEmailAsync(userInfo.EmailAddress);
77 | var claimsDB = await _userManager.GetClaimsAsync(identityUser);
78 |
79 | claims.AddRange(claimsDB);
80 |
81 | var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWTkey"]));
82 | var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
83 |
84 | var expiration = DateTime.UtcNow.AddYears(1);
85 |
86 | JwtSecurityToken token = new JwtSecurityToken(
87 | issuer: null,
88 | audience: null,
89 | claims: claims,
90 | expires: expiration,
91 | signingCredentials: creds);
92 |
93 | return new UserToken()
94 | {
95 | Token = new JwtSecurityTokenHandler().WriteToken(token),
96 | Expiration = expiration
97 | };
98 |
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/Controllers/PeopleController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Authentication.JwtBearer;
3 | using Microsoft.AspNetCore.Authorization;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.EntityFrameworkCore;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Threading.Tasks;
10 |
11 | namespace API.Controllers
12 | {
13 | [ApiController]
14 | [Route("api/people")]
15 | public class PeopleController: ControllerBase
16 | {
17 | private readonly ApplicationDbContext context;
18 |
19 | public PeopleController(ApplicationDbContext context)
20 | {
21 | this.context = context;
22 | }
23 |
24 | [HttpGet]
25 | public async Task>> Get()
26 | {
27 | return await context.People.ToListAsync();
28 | }
29 |
30 | [HttpPost]
31 | [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
32 | public async Task> Post(Person person)
33 | {
34 | context.Add(person);
35 | await context.SaveChangesAsync();
36 | return person.Id;
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 |
8 | namespace API.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get([FromHeader] int weatherAmount = 5)
28 | {
29 |
30 | // Note: another way of getting a header from the request
31 | //var weatherAmount2 = int.Parse(HttpContext.Request.Headers["weatherAmount"].ToString());
32 |
33 | var rng = new Random();
34 | return Enumerable.Range(1, weatherAmount).Select(index => new WeatherForecast
35 | {
36 | Date = DateTime.Now.AddDays(index),
37 | TemperatureC = rng.Next(-20, 55),
38 | Summary = Summaries[rng.Next(Summaries.Length)]
39 | })
40 | .ToArray();
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Hosting;
2 | using Microsoft.Extensions.Configuration;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Logging;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace API
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:58393",
8 | "sslPort": 44337
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "API": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.JwtBearer;
2 | using Microsoft.AspNetCore.Builder;
3 | using Microsoft.AspNetCore.Hosting;
4 | using Microsoft.AspNetCore.HttpsPolicy;
5 | using Microsoft.AspNetCore.Identity;
6 | using Microsoft.AspNetCore.Mvc;
7 | using Microsoft.EntityFrameworkCore;
8 | using Microsoft.Extensions.Configuration;
9 | using Microsoft.Extensions.DependencyInjection;
10 | using Microsoft.Extensions.Hosting;
11 | using Microsoft.Extensions.Logging;
12 | using Microsoft.IdentityModel.Tokens;
13 | using Microsoft.OpenApi.Models;
14 | using System;
15 | using System.Collections.Generic;
16 | using System.Linq;
17 | using System.Text;
18 | using System.Threading.Tasks;
19 |
20 | namespace API
21 | {
22 | public class Startup
23 | {
24 | public Startup(IConfiguration configuration)
25 | {
26 | Configuration = configuration;
27 | }
28 |
29 | public IConfiguration Configuration { get; }
30 |
31 | // This method gets called by the runtime. Use this method to add services to the container.
32 | public void ConfigureServices(IServiceCollection services)
33 | {
34 | services.AddDbContext(options => options.UseInMemoryDatabase("mydatabase"));
35 | services.AddControllers();
36 | services.AddSwaggerGen(c =>
37 | {
38 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
39 | });
40 |
41 | services.AddIdentity()
42 | .AddEntityFrameworkStores()
43 | .AddDefaultTokenProviders();
44 |
45 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
46 | .AddJwtBearer(options =>
47 | options.TokenValidationParameters = new TokenValidationParameters
48 | {
49 | ValidateIssuer = false,
50 | ValidateAudience = false,
51 | ValidateLifetime = true,
52 | ValidateIssuerSigningKey = true,
53 | IssuerSigningKey = new SymmetricSecurityKey(
54 | Encoding.UTF8.GetBytes(Configuration["jwtkey"])),
55 | ClockSkew = TimeSpan.Zero
56 | }
57 | );
58 |
59 | }
60 |
61 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
62 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
63 | {
64 | if (env.IsDevelopment())
65 | {
66 | app.UseDeveloperExceptionPage();
67 | app.UseSwagger();
68 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
69 | }
70 |
71 | app.UseHttpsRedirection();
72 |
73 | app.UseRouting();
74 |
75 | app.UseAuthorization();
76 |
77 | app.UseEndpoints(endpoints =>
78 | {
79 | endpoints.MapControllers();
80 | });
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace API
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "JWTkey": "ASKMDLAMSLK3MLK3M4LK23M4LK23MLKMLFKDSMDFLKSDMFLKM33SDS",
3 | "Logging": {
4 | "LogLevel": {
5 | "Default": "Information",
6 | "Microsoft": "Warning",
7 | "Microsoft.Hosting.Lifetime": "Information"
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/Common/Person.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel.DataAnnotations;
3 |
4 | namespace Common
5 | {
6 | public class Person
7 | {
8 | public int Id { get; set; }
9 | [Required]
10 | public string Name { get; set; }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/Common/UserInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel.DataAnnotations;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace Common
9 | {
10 | public class UserInfo
11 | {
12 | [Required]
13 | [EmailAddress]
14 | public string EmailAddress { get; set; }
15 | [Required]
16 | public string Password { get; set; }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/Common/UserToken.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace Common
8 | {
9 | public class UserToken
10 | {
11 | public string Token { get; set; }
12 | public DateTime Expiration { get; set; }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/Common/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Common
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/HttpClientTutorial.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30804.86
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TheConsole", "TheConsole\TheConsole.csproj", "{3555DFEA-3E28-4519-95E3-5DA41622D4FF}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{D62139AC-C84A-4086-A4E2-EC9845A95CAF}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{058D1032-8480-4581-B6E3-EA7B704E233E}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {3555DFEA-3E28-4519-95E3-5DA41622D4FF}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {D62139AC-C84A-4086-A4E2-EC9845A95CAF}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {058D1032-8480-4581-B6E3-EA7B704E233E}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {1A7A7613-556B-4F6B-8684-057AD8B535C0}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/TheConsole/Program.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net;
5 | using System.Net.Http;
6 | using System.Net.Http.Headers;
7 | using System.Net.Http.Json;
8 | using System.Text;
9 | using System.Text.Json;
10 | using System.Threading.Tasks;
11 |
12 | namespace TheConsole
13 | {
14 | class Program
15 | {
16 | static string urlAccounts = "https://localhost:5001/api/accounts";
17 | static UserInfo credentials = new UserInfo() { EmailAddress = "felipe@hotmail.com", Password = "aA123456!" };
18 | static async Task Main(string[] args)
19 | {
20 | var urlPeople = "https://localhost:5001/api/people";
21 | var jsonSerializerOptions = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
22 | var urlExample1 = "https://localhost:5001/WeatherForecast";
23 |
24 | using (var httpClient = new HttpClient())
25 | {
26 | // example 1: Sending a value on the header once
27 | // Ideal when we don't want to affect other HTTP requests
28 |
29 | using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, urlExample1))
30 | {
31 | requestMessage.Headers.Add("weatherAmount", "10");
32 | var responseExample1 = await httpClient.SendAsync(requestMessage);
33 | var weatherForecasts = JsonSerializer.Deserialize>(
34 | await responseExample1.Content.ReadAsStringAsync(), jsonSerializerOptions);
35 | Console.WriteLine($"Amount of Weather data #1: {weatherForecasts.Count}");
36 | }
37 |
38 | var weatherForecasts2 = await httpClient.GetFromJsonAsync>(urlExample1,
39 | jsonSerializerOptions);
40 | Console.WriteLine($"Amount of Weather data #2: {weatherForecasts2.Count}");
41 |
42 | // example 2: Modifying the headers of all of the requests
43 | httpClient.DefaultRequestHeaders.Add("weatherAmount", "30");
44 |
45 | var weatherForecasts3 = await httpClient.GetFromJsonAsync>(urlExample1,
46 | jsonSerializerOptions);
47 | Console.WriteLine($"Amount of Weather data #3: {weatherForecasts3.Count}");
48 |
49 | var weatherForecasts4 = await httpClient.GetFromJsonAsync>(urlExample1,
50 | jsonSerializerOptions);
51 | Console.WriteLine($"Amount of Weather data #4: {weatherForecasts4.Count}");
52 |
53 | // example 3: JWT
54 | await CreateUser();
55 | var httpResponseToken = await httpClient.PostAsJsonAsync($"{urlAccounts}/login", credentials);
56 | var responseToken = JsonSerializer.Deserialize(await
57 | httpResponseToken.Content.ReadAsStringAsync(), jsonSerializerOptions);
58 |
59 | httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer",
60 | responseToken.Token);
61 |
62 | var response = await httpClient.PostAsJsonAsync(urlPeople, new Person() { Name = "Felipe" });
63 | response.EnsureSuccessStatusCode();
64 | Console.WriteLine("Person created successfully");
65 |
66 | }
67 |
68 | }
69 |
70 | private async static Task CreateUser()
71 | {
72 | try
73 | {
74 | using (var httpClient = new HttpClient())
75 | {
76 | var respuesta = await httpClient.PostAsJsonAsync($"{urlAccounts}/create", credentials);
77 | if (respuesta.StatusCode == HttpStatusCode.InternalServerError)
78 | {
79 | respuesta.EnsureSuccessStatusCode();
80 | }
81 | }
82 | }
83 | catch (Exception e)
84 | {
85 | Console.WriteLine(e);
86 | }
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/TheConsole/TheConsole.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Video 3 - HTTP Request Headers/End/TheConsole/Utils.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Text.Json;
6 | using System.Threading.Tasks;
7 |
8 | namespace TheConsole
9 | {
10 | public class Utils
11 | {
12 | public static Dictionary> ExtractErrorsFromWebAPIResponse(string body)
13 | {
14 | var response = new Dictionary>();
15 |
16 | var jsonElement = JsonSerializer.Deserialize(body);
17 | var errorsJsonElement = jsonElement.GetProperty("errors");
18 | foreach (var fieldWithErrors in errorsJsonElement.EnumerateObject())
19 | {
20 | var field = fieldWithErrors.Name;
21 | var errors = new List();
22 | foreach (var errorKind in fieldWithErrors.Value.EnumerateArray())
23 | {
24 | var error = errorKind.GetString();
25 | errors.Add(error);
26 | }
27 | response.Add(field, errors);
28 | }
29 |
30 | return response;
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/ApplicationDbContext.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
3 | using Microsoft.EntityFrameworkCore;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Diagnostics.CodeAnalysis;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace HttpClientDemo.API
11 | {
12 | public class ApplicationDbContext : IdentityDbContext
13 | {
14 | public ApplicationDbContext([NotNull] DbContextOptions options) : base(options)
15 | {
16 | }
17 |
18 | protected override void OnModelCreating(ModelBuilder modelBuilder)
19 | {
20 | base.OnModelCreating(modelBuilder);
21 | }
22 |
23 | public DbSet People { get; set; }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/Controllers/PeopleController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Authentication.JwtBearer;
3 | using Microsoft.AspNetCore.Authorization;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.EntityFrameworkCore;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Threading.Tasks;
10 |
11 | namespace HttpClientDemo.API.Controllers
12 | {
13 | [ApiController]
14 | [Route("api/people")]
15 | public class PeopleController : ControllerBase
16 | {
17 | private readonly ApplicationDbContext context;
18 |
19 | public PeopleController(ApplicationDbContext context)
20 | {
21 | this.context = context;
22 | }
23 |
24 | [HttpGet]
25 | public async Task>> Get()
26 | {
27 | Console.WriteLine("get");
28 |
29 | return await context.People.ToListAsync();
30 | }
31 |
32 | [HttpPost]
33 | public async Task> Post(Person person)
34 | {
35 | context.Add(person);
36 | await context.SaveChangesAsync();
37 | return person.Id;
38 | }
39 |
40 | [HttpPut("{id:int}")]
41 | public async Task Put(int id, Person person)
42 | {
43 | var personExists = await PersonExists(id);
44 |
45 | if (!personExists)
46 | {
47 | return NotFound();
48 | }
49 |
50 | context.Update(person);
51 | await context.SaveChangesAsync();
52 | return NoContent();
53 | }
54 |
55 | [HttpDelete("{id:int}")]
56 | public async Task Delete(int id)
57 | {
58 | var personExists = await PersonExists(id);
59 |
60 | if (!personExists)
61 | {
62 | return NotFound();
63 | }
64 |
65 | context.Remove(new Person() { Id = id });
66 | await context.SaveChangesAsync();
67 | return NoContent();
68 | }
69 |
70 | private async Task PersonExists(int id)
71 | {
72 | return await context.People.AnyAsync(p => p.Id == id);
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 |
8 | namespace HttpClientDemo.API.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get([FromHeader] int cantidadElementos = 5)
28 | {
29 |
30 | // Nota: esta es otra manera de acceder al valor de la cabecera:
31 | //var cantidadElementos2 = int.Parse(HttpContext.Request.Headers["cantidadElementos"].ToString());
32 |
33 | var rng = new Random();
34 | return Enumerable.Range(1, cantidadElementos).Select(index => new WeatherForecast
35 | {
36 | Date = DateTime.Now.AddDays(index),
37 | TemperatureC = rng.Next(-20, 55),
38 | Summary = Summaries[rng.Next(Summaries.Length)]
39 | })
40 | .ToArray();
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Hosting;
2 | using Microsoft.Extensions.Configuration;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Logging;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace HttpClientDemo.API
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:56764",
8 | "sslPort": 44301
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "HttpClientDemo.API": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.JwtBearer;
2 | using Microsoft.AspNetCore.Builder;
3 | using Microsoft.AspNetCore.Hosting;
4 | using Microsoft.AspNetCore.HttpsPolicy;
5 | using Microsoft.AspNetCore.Identity;
6 | using Microsoft.AspNetCore.Mvc;
7 | using Microsoft.EntityFrameworkCore;
8 | using Microsoft.Extensions.Configuration;
9 | using Microsoft.Extensions.DependencyInjection;
10 | using Microsoft.Extensions.Hosting;
11 | using Microsoft.Extensions.Logging;
12 | using Microsoft.IdentityModel.Tokens;
13 | using Microsoft.OpenApi.Models;
14 | using System;
15 | using System.Collections.Generic;
16 | using System.Linq;
17 | using System.Text;
18 | using System.Threading.Tasks;
19 |
20 | namespace HttpClientDemo.API
21 | {
22 | public class Startup
23 | {
24 | public Startup(IConfiguration configuration)
25 | {
26 | Configuration = configuration;
27 | }
28 |
29 | public IConfiguration Configuration { get; }
30 |
31 | // This method gets called by the runtime. Use this method to add services to the container.
32 | public void ConfigureServices(IServiceCollection services)
33 | {
34 | services.AddDbContext(options => options.UseInMemoryDatabase("database"));
35 | services.AddControllers();
36 | services.AddSwaggerGen(c =>
37 | {
38 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "HttpClientDemo.API", Version = "v1" });
39 | });
40 |
41 | services.AddIdentity()
42 | .AddEntityFrameworkStores()
43 | .AddDefaultTokenProviders();
44 |
45 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
46 | .AddJwtBearer(options =>
47 | options.TokenValidationParameters = new TokenValidationParameters
48 | {
49 | ValidateIssuer = false,
50 | ValidateAudience = false,
51 | ValidateLifetime = true,
52 | ValidateIssuerSigningKey = true,
53 | IssuerSigningKey = new SymmetricSecurityKey(
54 | Encoding.UTF8.GetBytes(Configuration["jwtkey"])),
55 | ClockSkew = TimeSpan.Zero
56 | }
57 | );
58 |
59 | }
60 |
61 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
62 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
63 | {
64 | if (env.IsDevelopment())
65 | {
66 | app.UseDeveloperExceptionPage();
67 | app.UseSwagger();
68 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "HttpClientDemo.API v1"));
69 | }
70 |
71 | app.UseHttpsRedirection();
72 |
73 | app.UseRouting();
74 |
75 | app.UseAuthorization();
76 |
77 | app.UseEndpoints(endpoints =>
78 | {
79 | endpoints.MapControllers();
80 | });
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace HttpClientDemo.API
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "JWTkey": "askrm3k4m23lk4m23lk4mlkMLKASML32K4M3L2K4M23442342653442354233NSKDMASKDM",
3 | "Logging": {
4 | "LogLevel": {
5 | "Default": "Information",
6 | "Microsoft": "Warning",
7 | "Microsoft.Hosting.Lifetime": "Information"
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/Common/Person.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel.DataAnnotations;
3 |
4 | namespace Common
5 | {
6 | public class Person
7 | {
8 | public int Id { get; set; }
9 | [Required]
10 | public string Name { get; set; }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/Common/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Common
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/HttpClientDemo.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30804.86
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{7A363275-3931-43E7-89F9-6FF43A3EF7E8}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "Common\Common.csproj", "{4476A2FC-74F2-4B82-8F52-60BACBD8C715}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TheConsole", "TheConsole\TheConsole.csproj", "{59CBC5C4-973A-45DC-B227-2FE38E4BCA33}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {7A363275-3931-43E7-89F9-6FF43A3EF7E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {7A363275-3931-43E7-89F9-6FF43A3EF7E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {7A363275-3931-43E7-89F9-6FF43A3EF7E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {7A363275-3931-43E7-89F9-6FF43A3EF7E8}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {4476A2FC-74F2-4B82-8F52-60BACBD8C715}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {4476A2FC-74F2-4B82-8F52-60BACBD8C715}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {4476A2FC-74F2-4B82-8F52-60BACBD8C715}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {4476A2FC-74F2-4B82-8F52-60BACBD8C715}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {59CBC5C4-973A-45DC-B227-2FE38E4BCA33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {59CBC5C4-973A-45DC-B227-2FE38E4BCA33}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {59CBC5C4-973A-45DC-B227-2FE38E4BCA33}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {59CBC5C4-973A-45DC-B227-2FE38E4BCA33}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {A9D552E4-4B3B-4E0E-833D-A2C841C15E1D}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/TheConsole/Program.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net.Http;
5 | using System.Net.Http.Json;
6 | using System.Threading.Tasks;
7 |
8 | namespace HttpClientDemo.TheConsole
9 | {
10 | class Program
11 | {
12 | static async Task Main(string[] args)
13 | {
14 | var peopleURL = "https://localhost:5001/api/people";
15 |
16 | using (var httpClient = new HttpClient())
17 | {
18 | var person = new Person() { Name = "Felipe Gavilán" };
19 |
20 | // Creating the person
21 | var responseMessage = await httpClient.PostAsJsonAsync(peopleURL, person);
22 | responseMessage.EnsureSuccessStatusCode();
23 | var content = await responseMessage.Content.ReadAsStringAsync();
24 | var personId = int.Parse(content);
25 |
26 | // Example 1: Make an HTTP PUT
27 | }
28 |
29 | Console.Read();
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/Begin/TheConsole/TheConsole.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/ApplicationDbContext.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
3 | using Microsoft.EntityFrameworkCore;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Diagnostics.CodeAnalysis;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace HttpClientDemo.API
11 | {
12 | public class ApplicationDbContext : IdentityDbContext
13 | {
14 | public ApplicationDbContext([NotNull] DbContextOptions options) : base(options)
15 | {
16 | }
17 |
18 | protected override void OnModelCreating(ModelBuilder modelBuilder)
19 | {
20 | base.OnModelCreating(modelBuilder);
21 | }
22 |
23 | public DbSet People { get; set; }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/Controllers/PeopleController.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using Microsoft.AspNetCore.Authentication.JwtBearer;
3 | using Microsoft.AspNetCore.Authorization;
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.EntityFrameworkCore;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Threading.Tasks;
10 |
11 | namespace HttpClientDemo.API.Controllers
12 | {
13 | [ApiController]
14 | [Route("api/people")]
15 | public class PeopleController : ControllerBase
16 | {
17 | private readonly ApplicationDbContext context;
18 |
19 | public PeopleController(ApplicationDbContext context)
20 | {
21 | this.context = context;
22 | }
23 |
24 | [HttpGet]
25 | public async Task>> Get()
26 | {
27 | Console.WriteLine("get");
28 |
29 | return await context.People.ToListAsync();
30 | }
31 |
32 | [HttpPost]
33 | public async Task> Post(Person person)
34 | {
35 | context.Add(person);
36 | await context.SaveChangesAsync();
37 | return person.Id;
38 | }
39 |
40 | [HttpPut("{id:int}")]
41 | public async Task Put(int id, Person person)
42 | {
43 | var personExists = await PersonExists(id);
44 |
45 | if (!personExists)
46 | {
47 | return NotFound();
48 | }
49 |
50 | context.Update(person);
51 | await context.SaveChangesAsync();
52 | return NoContent();
53 | }
54 |
55 | [HttpDelete("{id:int}")]
56 | public async Task Delete(int id)
57 | {
58 | var personExists = await PersonExists(id);
59 |
60 | if (!personExists)
61 | {
62 | return NotFound();
63 | }
64 |
65 | context.Remove(new Person() { Id = id });
66 | await context.SaveChangesAsync();
67 | return NoContent();
68 | }
69 |
70 | private async Task PersonExists(int id)
71 | {
72 | return await context.People.AnyAsync(p => p.Id == id);
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc;
2 | using Microsoft.Extensions.Logging;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 |
8 | namespace HttpClientDemo.API.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get([FromHeader] int cantidadElementos = 5)
28 | {
29 |
30 | // Nota: esta es otra manera de acceder al valor de la cabecera:
31 | //var cantidadElementos2 = int.Parse(HttpContext.Request.Headers["cantidadElementos"].ToString());
32 |
33 | var rng = new Random();
34 | return Enumerable.Range(1, cantidadElementos).Select(index => new WeatherForecast
35 | {
36 | Date = DateTime.Now.AddDays(index),
37 | TemperatureC = rng.Next(-20, 55),
38 | Summary = Summaries[rng.Next(Summaries.Length)]
39 | })
40 | .ToArray();
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Hosting;
2 | using Microsoft.Extensions.Configuration;
3 | using Microsoft.Extensions.Hosting;
4 | using Microsoft.Extensions.Logging;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace HttpClientDemo.API
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:56764",
8 | "sslPort": 44301
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "swagger",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "HttpClientDemo.API": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": "true",
23 | "launchBrowser": true,
24 | "launchUrl": "swagger",
25 | "applicationUrl": "https://localhost:5001;http://localhost:5000",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication.JwtBearer;
2 | using Microsoft.AspNetCore.Builder;
3 | using Microsoft.AspNetCore.Hosting;
4 | using Microsoft.AspNetCore.HttpsPolicy;
5 | using Microsoft.AspNetCore.Identity;
6 | using Microsoft.AspNetCore.Mvc;
7 | using Microsoft.EntityFrameworkCore;
8 | using Microsoft.Extensions.Configuration;
9 | using Microsoft.Extensions.DependencyInjection;
10 | using Microsoft.Extensions.Hosting;
11 | using Microsoft.Extensions.Logging;
12 | using Microsoft.IdentityModel.Tokens;
13 | using Microsoft.OpenApi.Models;
14 | using System;
15 | using System.Collections.Generic;
16 | using System.Linq;
17 | using System.Text;
18 | using System.Threading.Tasks;
19 |
20 | namespace HttpClientDemo.API
21 | {
22 | public class Startup
23 | {
24 | public Startup(IConfiguration configuration)
25 | {
26 | Configuration = configuration;
27 | }
28 |
29 | public IConfiguration Configuration { get; }
30 |
31 | // This method gets called by the runtime. Use this method to add services to the container.
32 | public void ConfigureServices(IServiceCollection services)
33 | {
34 | services.AddDbContext(options => options.UseInMemoryDatabase("database"));
35 | services.AddControllers();
36 | services.AddSwaggerGen(c =>
37 | {
38 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "HttpClientDemo.API", Version = "v1" });
39 | });
40 |
41 | services.AddIdentity()
42 | .AddEntityFrameworkStores()
43 | .AddDefaultTokenProviders();
44 |
45 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
46 | .AddJwtBearer(options =>
47 | options.TokenValidationParameters = new TokenValidationParameters
48 | {
49 | ValidateIssuer = false,
50 | ValidateAudience = false,
51 | ValidateLifetime = true,
52 | ValidateIssuerSigningKey = true,
53 | IssuerSigningKey = new SymmetricSecurityKey(
54 | Encoding.UTF8.GetBytes(Configuration["jwtkey"])),
55 | ClockSkew = TimeSpan.Zero
56 | }
57 | );
58 |
59 | }
60 |
61 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
62 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
63 | {
64 | if (env.IsDevelopment())
65 | {
66 | app.UseDeveloperExceptionPage();
67 | app.UseSwagger();
68 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "HttpClientDemo.API v1"));
69 | }
70 |
71 | app.UseHttpsRedirection();
72 |
73 | app.UseRouting();
74 |
75 | app.UseAuthorization();
76 |
77 | app.UseEndpoints(endpoints =>
78 | {
79 | endpoints.MapControllers();
80 | });
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace HttpClientDemo.API
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "JWTkey": "askrm3k4m23lk4m23lk4mlkMLKASML32K4M3L2K4M23442342653442354233NSKDMASKDM",
3 | "Logging": {
4 | "LogLevel": {
5 | "Default": "Information",
6 | "Microsoft": "Warning",
7 | "Microsoft.Hosting.Lifetime": "Information"
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/Common/Common.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/Common/Person.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel.DataAnnotations;
3 |
4 | namespace Common
5 | {
6 | public class Person
7 | {
8 | public int Id { get; set; }
9 | [Required]
10 | public string Name { get; set; }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/Common/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Common
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/HttpClientDemo.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30804.86
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{7A363275-3931-43E7-89F9-6FF43A3EF7E8}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common", "Common\Common.csproj", "{4476A2FC-74F2-4B82-8F52-60BACBD8C715}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TheConsole", "TheConsole\TheConsole.csproj", "{59CBC5C4-973A-45DC-B227-2FE38E4BCA33}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {7A363275-3931-43E7-89F9-6FF43A3EF7E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {7A363275-3931-43E7-89F9-6FF43A3EF7E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {7A363275-3931-43E7-89F9-6FF43A3EF7E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {7A363275-3931-43E7-89F9-6FF43A3EF7E8}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {4476A2FC-74F2-4B82-8F52-60BACBD8C715}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {4476A2FC-74F2-4B82-8F52-60BACBD8C715}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {4476A2FC-74F2-4B82-8F52-60BACBD8C715}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {4476A2FC-74F2-4B82-8F52-60BACBD8C715}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {59CBC5C4-973A-45DC-B227-2FE38E4BCA33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {59CBC5C4-973A-45DC-B227-2FE38E4BCA33}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {59CBC5C4-973A-45DC-B227-2FE38E4BCA33}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {59CBC5C4-973A-45DC-B227-2FE38E4BCA33}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {A9D552E4-4B3B-4E0E-833D-A2C841C15E1D}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/TheConsole/Program.cs:
--------------------------------------------------------------------------------
1 | using Common;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Net.Http;
5 | using System.Net.Http.Json;
6 | using System.Threading.Tasks;
7 |
8 | namespace HttpClientDemo.TheConsole
9 | {
10 | class Program
11 | {
12 | static async Task Main(string[] args)
13 | {
14 | var peopleURL = "https://localhost:44301/api/people";
15 |
16 | using (var httpClient = new HttpClient())
17 | {
18 | var person = new Person() { Name = "Felipe Gavilán" };
19 |
20 | // Creating the person
21 | var responseMessage = await httpClient.PostAsJsonAsync(peopleURL, person);
22 | responseMessage.EnsureSuccessStatusCode();
23 | var content = await responseMessage.Content.ReadAsStringAsync();
24 | var personId = int.Parse(content);
25 |
26 | // Example 1: Make an HTTP PUT
27 | person.Id = personId;
28 | person.Name = "Updated";
29 | await httpClient.PutAsJsonAsync($"{peopleURL}/{personId}", person);
30 |
31 | var people = await httpClient.GetFromJsonAsync>(peopleURL);
32 |
33 | foreach (var p in people)
34 | {
35 | Console.WriteLine($"Id: {p.Id} - Name: {p.Name}");
36 | }
37 |
38 | // Example 2: Make an HTTP DELETE
39 |
40 | await httpClient.DeleteAsync($"{peopleURL}/{personId}");
41 | var people2 = await httpClient.GetFromJsonAsync>(peopleURL);
42 | if (people2.Count == 0)
43 | {
44 | Console.WriteLine($"There are no records in the table");
45 | }
46 | }
47 |
48 | Console.WriteLine("The end");
49 |
50 | Console.Read();
51 | }
52 | }
53 | }
--------------------------------------------------------------------------------
/Video 4 - HTTP PUT and HTTP DELETE/End/TheConsole/TheConsole.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------