### HttpRepl Settings Example Source: https://learn.microsoft.com/en-us/aspnet/core/web-api/http-repl Example output of the 'pref get' command, displaying various color settings for JSON output and protocol information. ```console colors.json=Green colors.json.arrayBrace=BoldCyan colors.json.comma=BoldYellow colors.json.name=BoldMagenta colors.json.nameSeparator=BoldWhite colors.json.objectBrace=Cyan colors.protocol=BoldGreen colors.status=BoldYellow ``` -------------------------------- ### Visual Studio Setup Script Source: https://learn.microsoft.com/en-us/aspnet/visual-studio/overview/2013/visual-studio-2013-web-tools This script configures the environment and installs Visual Studio code snippets for the hands-on lab. Run it as administrator. ```batch Setup.cmd ``` -------------------------------- ### Implement Custom Initialization Logic Source: https://learn.microsoft.com/en-us/aspnet/whitepapers/aspnet4/overview This C# code example shows how to implement the `IProcessHostPreloadClient` interface to define custom initialization logic that runs when an application starts. ```C# public class CustomInitialization : System.Web.Hosting.IProcessHostPreloadClient { public void Preload(string[] parameters) { // Perform initialization. } } ``` -------------------------------- ### Enable and Start the Service Source: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-apache Enable the service to start on boot and then start the service immediately. Verify its status to ensure it's running. ```bash sudo systemctl enable kestrel-helloapp.service sudo systemctl start kestrel-helloapp.service sudo systemctl status kestrel-helloapp.service ``` -------------------------------- ### Call JSExported Method after Runtime Start Source: https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/startup The `onRuntimeReady` initializer is called after the .NET WebAssembly runtime has started. This example demonstrates how to get the configuration and potentially call a JSExported method before the Main method is invoked. ```javascript export function onRuntimeReady({ getAssemblyExports, getConfig }) { // Sample: After the runtime starts, but before Main method is called, // call [JSExport]ed method. const config = getConfig(); ``` -------------------------------- ### ASP.NET Core 2.2 Startup.Configure Example Source: https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30 An example of the `Startup.Configure` method in a typical ASP.NET Core 2.2 application, demonstrating the older middleware configuration. ```csharp public void Configure(IApplicationBuilder app) { ... app.UseStaticFiles(); app.UseAuthentication(); app.UseSignalR(hubs => { hubs.MapHub("/chat"); }); app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); } ``` -------------------------------- ### Custom Host Example for Web API Source: https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/an-overview-of-project-katana This code demonstrates a custom host setup for a Web API application using HttpSelfHostServer. It configures routes and starts the server, listening on a specified base address. ```C# static void Main() { var baseAddress = new Uri("http://localhost:5000"); var config = new HttpSelfHostConfiguration(baseAddress); config.Routes.MapHttpRoute("default", "{controller}"); using (var svr = new HttpSelfHostServer(config)) { svr.OpenAsync().Wait(); Console.WriteLine("Press Enter to quit."); Console.ReadLine(); } } ``` -------------------------------- ### Program.cs with Startup Integration Source: https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60 Shows how `Program.cs` integrates with the `Startup` class in the minimal hosting model. The `Startup` class is instantiated, its services are configured, and its `Configure` method is called. ```csharp using Microsoft.AspNetCore.Builder; var builder = WebApplication.CreateBuilder(args); var startup = new Startup(builder.Configuration); startup.ConfigureServices(builder.Services); var app = builder.Build(); startup.Configure(app, app.Environment); app.MapRazorPages(); app.Run(); ``` -------------------------------- ### HTTP GET Request Example Source: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api This example demonstrates how to generate an HTTP GET request for the `/api/todoitems` endpoint within the `TodoApi.http` file. This is typically used for retrieving a list of items. ```http GET {{TodoApi_HostAddress}}/api/todoitems ``` -------------------------------- ### Create a default web host builder Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host This snippet shows the typical setup of a web host in the `Main` method of `Program.cs` using `WebHost.CreateDefaultBuilder` and specifying a `Startup` class. ```csharp public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup(); } ``` -------------------------------- ### Issue an HTTP GET request Source: https://learn.microsoft.com/en-us/aspnet/core/web-api/http-repl Use the `get` command to issue an HTTP GET request to an endpoint. This example shows retrieving all records. ```console https://localhost:5001/people> get ``` ```console HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Date: Fri, 21 Jun 2019 03:38:45 GMT Server: Kestrel Transfer-Encoding: chunked [ { "id": 1, "name": "Scott Hunter" }, { "id": 2, "name": "Scott Hanselman" }, { "id": 3, "name": "Scott Guthrie" } ] https://localhost:5001/people> ``` -------------------------------- ### SignalR Client Library Installation Output Source: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr Example output from the libman install command, indicating the successful installation of the SignalR client library files. ```Console wwwroot/js/signalr/dist/browser/signalr.js written to disk wwwroot/js/signalr/dist/browser/signalr.js written to disk Installed library "@microsoft/signalr@latest" to "wwwroot/js/signalr" ``` -------------------------------- ### Configure Production Startup via web.config Source: https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection Demonstrates various ways to specify the ProductionStartup class in web.config, including by fully qualified name, assembly-qualified name, and specifying the configuration method. ```XML ``` ```XML ``` ```XML ``` -------------------------------- ### Migrated Program.cs for Minimal Hosting Model Source: https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60 This code shows how to migrate the `Startup` class logic to the new minimal hosting model in `Program.cs`. ```csharp using Microsoft.AspNetCore.Builder; var builder = WebApplication.CreateBuilder(args); var startup = new Startup(builder.Configuration); startup.ConfigureServices(builder.Services); var app = builder.Build(); startup.Configure(app, app.Environment); app.Run(); ``` -------------------------------- ### Unauthorized HTTP GET Request Example Source: https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api This is an example of an HTTP GET request made to a Web API endpoint without an access token. The server responds with a 401 Unauthorized status because the Authorization header is missing. ```http GET https://localhost:44305/api/values HTTP/1.1 Host: localhost:44305 User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0 Accept: */* Accept-Language: en-US,en;q=0.5 X-Requested-With: XMLHttpRequest Referer: https://localhost:44305/ ``` -------------------------------- ### Install Client-Side Routing Package (Angular Example) Source: https://learn.microsoft.com/en-us/aspnet/core/client-side/spa-services Install the client-side routing package, such as @angular/router for Angular, as a dependency. ```bash npm i -S @angular/router ``` -------------------------------- ### Configure Hosting Startup Configuration Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/platform-specific-configuration Implement `IHostingStartup` to configure application settings. Use `ConfigureAppConfiguration` for higher priority settings and `UseConfiguration` for lower priority settings. ```csharp public class ConfigurationInjection : IHostingStartup { public void Configure(IWebHostBuilder builder) { Dictionary dict; builder.ConfigureAppConfiguration(config => { dict = new Dictionary { {"ConfigurationKey1", "From IHostingStartup: Higher priority " + "than the app's configuration."}, }; config.AddInMemoryCollection(dict); }); dict = new Dictionary { {"ConfigurationKey2", "From IHostingStartup: Lower priority " + "than the app's configuration."}, }; var builtConfig = new ConfigurationBuilder() .AddInMemoryCollection(dict) .Build(); builder.UseConfiguration(builtConfig); } } ``` -------------------------------- ### LibMan Install Example with CDNJS Source: https://learn.microsoft.com/en-us/aspnet/core/client-side/libman/libman-cli Installs a specific jQuery file from CDNJS to a designated folder, updating libman.json. ```bash libman install jquery@3.2.1 --provider cdnjs --destination wwwroot/scripts/jquery --files jquery.min.js ``` ```json { "version": "1.0", "defaultProvider": "cdnjs", "libraries": [ { "library": "jquery@3.2.1", "destination": "wwwroot/scripts/jquery", "files": [ "jquery.min.js" ] } ] } ``` -------------------------------- ### Example: Create Infrastructure with Windows Authentication Source: https://learn.microsoft.com/en-us/aspnet/web-forms/overview/data-access/caching-data/using-sql-cache-dependencies-cs This example demonstrates how to set up the polling infrastructure for SQL cache dependencies on a specific database and server using Windows Authentication. ```Console aspnet_regsql.exe -S ScottsServer -E -d pubs -ed ``` -------------------------------- ### HTTP Logging Output Example Source: https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-6.0 Example of the log output generated by the HTTP logging middleware for a GET request. ```log info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1] Request: Protocol: HTTP/2 Method: GET Scheme: https PathBase: Path: / Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Cache-Control: max-age=0 Connection: close Cookie: [Redacted] Host: localhost:44372 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30 sec-ch-ua: [Redacted] sec-ch-ua-mobile: [Redacted] sec-ch-ua-platform: [Redacted] upgrade-insecure-requests: [Redacted] sec-fetch-site: [Redacted] sec-fetch-mode: [Redacted] sec-fetch-user: [Redacted] sec-fetch-dest: [Redacted] info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2] Response: StatusCode: 200 Content-Type: text/plain; charset=utf-8 ``` -------------------------------- ### Configure Method in Startup Class Source: https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60 Demonstrates the `Configure` method within the `Startup` class when migrating to the minimal hosting model. Note the commented-out calls to `UseRouting` and `UseEndpoints`. ```csharp public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (!env.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); //app.UseRouting(); //app.UseEndpoints(endpoints => //{ // endpoints.MapRazorPages(); //}); } } ``` -------------------------------- ### HTTP Request to Get Supplier Products Source: https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/entity-relations-in-odata-v4 Example HTTP GET request to retrieve all products associated with a specific supplier. ```http GET http://myproductservice.example.com/Suppliers(2)/Products HTTP/1.1 User-Agent: Fiddler Host: myproductservice.example.com ``` -------------------------------- ### Configure Hosting Startup Configuration Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/platform-specific-configuration Implement `IHostingStartup` to configure application settings. Use `ConfigureAppConfiguration` for higher priority and `UseConfiguration` for lower priority configuration. ```csharp public class ConfigurationInjection : IHostingStartup { public void Configure(IWebHostBuilder builder) { Dictionary dict; builder.ConfigureAppConfiguration(config => { dict = new Dictionary { {"ConfigurationKey1", "From IHostingStartup: Higher priority " + "than the app's configuration."}, }; config.AddInMemoryCollection(dict); }); dict = new Dictionary { {"ConfigurationKey2", "From IHostingStartup: Lower priority " + "than the app's configuration."}, }; var builtConfig = new ConfigurationBuilder() .AddInMemoryCollection(dict) .Build(); builder.UseConfiguration(builtConfig); } } ``` -------------------------------- ### GET Request Example Source: https://learn.microsoft.com/en-us/aspnet/core/security/cors Demonstrates a typical GET request made to a CORS-enabled endpoint, including request and response headers. ```http Request URL: https://cors1.azurewebsites.net/api/values Request Method: GET Status Code: 200 OK ``` ```http Content-Encoding: gzip Content-Type: text/plain; charset: utf-8 Server: Microsoft-IIS/10.0 Set-Cookie: ARRAffinity=8f...;Path=/;HttpOnly;Domain=cors1.azurewebsites.net Transfer-Encoding: chunked Vary: Accept-Encoding X-Powered-By: ASP.NET ``` ```http Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Connection: keep-alive Host: cors1.azurewebsites.net Origin: https://cors3.azurewebsites.net Referer: https://cors3.azurewebsites.net/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 ... ``` -------------------------------- ### Basic WebApplication setup with WebApplicationBuilder Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/webapplication This is the standard way to create a WebApplication using `WebApplicationBuilder`, as generated by the `dotnet new web` command or the Empty Web template in Visual Studio. ```csharp var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run(); ``` -------------------------------- ### Example Cross-Origin GET Request Source: https://learn.microsoft.com/en-us/aspnet/core/security/cors Demonstrates a typical cross-origin GET request, highlighting the Origin header sent by the browser. ```http Request URL: https://cors1.azurewebsites.net/api/values Request Method: GET Status Code: 200 OK Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Connection: keep-alive Host: cors1.azurewebsites.net Origin: https://cors3.azurewebsites.net Referer: https://cors3.azurewebsites.net/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 ... ``` -------------------------------- ### SignalR Client Library Installation Output Source: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr This is an example of the console output when the SignalR client library is successfully downloaded and installed using LibMan. ```console Downloading file https://unpkg.com/@microsoft/signalr@latest/dist/browser/signalr.js... wwwroot/js/signalr/dist/browser/signalr.js written to disk Installed library "@microsoft/signalr@latest" to "wwwroot/js/signalr" ``` -------------------------------- ### HttpClient with Client Options in SetUp/TearDown Source: https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests Illustrates setting up and tearing down an HttpClient with WebApplicationFactoryClientOptions using SetUp and TearDown methods. This approach ensures a fresh client instance for each test method and proper disposal. ```csharp public class IndexPageTests { private HttpClient _client; private CustomWebApplicationFactory _factory; [SetUp] public void SetUp() { _factory = new CustomWebApplicationFactory(); _client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); } [TearDown] public void TearDown() { _factory.Dispose(); _client.Dispose(); } ``` -------------------------------- ### Configuring WebHost with Startup Class (Throws Exception) Source: https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60 Illustrates an attempt to configure `WebHost` using a `Startup` class with `WebApplicationBuilder.Host`. This approach is no longer supported and will result in an exception. ```csharp var builder = WebApplication.CreateBuilder(args); try { builder.Host.ConfigureWebHostDefaults(webHostBuilder => { webHostBuilder.UseStartup(); }); } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } builder.Services.AddRazorPages(); var app = builder.Build(); ``` -------------------------------- ### LibMan Install Example with Filesystem Provider Source: https://learn.microsoft.com/en-us/aspnet/core/client-side/libman/libman-cli Installs multiple files from a local directory using the filesystem provider, prompting for destination if not specified. ```bash libman install C:\temp\contosoCalendar\ --provider filesystem --files calendar.js --files calendar.css ``` ```json { "version": "1.0", "defaultProvider": "cdnjs", "libraries": [ { "library": "jquery@3.2.1", "destination": "wwwroot/scripts/jquery", "files": [ "jquery.min.js" ] }, { "library": "C:\\temp\\contosoCalendar\\", "provider": "filesystem", "destination": "wwwroot/lib/contosoCalendar", "files": [ "calendar.js", "calendar.css" ] } ] } ``` -------------------------------- ### Retrieve a specific record with GET Source: https://learn.microsoft.com/en-us/aspnet/core/web-api/http-repl Use the `get` command with a parameter to retrieve a specific record. This example retrieves the record with ID 2. ```console https://localhost:5001/people> get 2 ``` ```console HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Date: Fri, 21 Jun 2019 06:17:57 GMT Server: Kestrel Transfer-Encoding: chunked [ { "id": 2, "name": "Scott Hanselman" } ] https://localhost:5001/people> ``` -------------------------------- ### Basic WebApp Builder Setup Source: https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets This C# code shows the default setup for a WebApplication builder, which includes registering configuration sources. ```C# var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run(); ``` -------------------------------- ### Example HTTP Request Source: https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-and-action-selection An example of an HTTP GET request to a local development server, including the path, query parameters, and version information. ```Console GET http://localhost:34701/api/products/1?version=1.5&details=1 ``` -------------------------------- ### Minimal API Setup with Custom Binding Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/parameter-binding Demonstrates setting up a Minimal API application and defining routes that utilize custom parameter binding. ```csharp using CustomBindingExample; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseHttpsRedirection(); app.MapGet("/", () => "Hello, IBindableFromHttpContext example!"); app.MapGet("/custom-binding", (CustomBoundParameter param) => { return $"Value from custom binding: {param.Value}"; }); app.MapGet("/combined/{id}", (int id, CustomBoundParameter param) => { return $"ID: {id}, Custom Value: {param.Value}"; }); ``` -------------------------------- ### ProductsController Example Source: https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api An example of a Web API controller that returns HttpResponseMessage. It demonstrates dependency injection for the repository and includes GET and POST methods. ```C# public class ProductsController : ApiController { IProductRepository _repository; public ProductsController(IProductRepository repository) { _repository = repository; } public HttpResponseMessage Get(int id) { Product product = _repository.GetById(id); if (product == null) { return Request.CreateResponse(HttpStatusCode.NotFound); } return Request.CreateResponse(product); } public HttpResponseMessage Post(Product product) { _repository.Add(product); var response = Request.CreateResponse(HttpStatusCode.Created, product); string uri = Url.Link("DefaultApi", new { id = product.Id }); response.Headers.Location = new Uri(uri); return response; } } ``` -------------------------------- ### Configure Hosting Startup Assemblies Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host Provides a semicolon-delimited string of hosting startup assemblies to load on startup using `UseSetting`. The app's assembly is always included. ```csharp WebHost.CreateDefaultBuilder(args) .UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "assembly1;assembly2") ``` -------------------------------- ### Project File for Hosting Startup Assembly Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/platform-specific-configuration This .NET SDK project file references the Microsoft.AspNetCore.Hosting.Abstractions package, which is necessary for creating a hosting startup assembly. ```XML netcoreapp3.0 ``` -------------------------------- ### Example HTTP GET Request Header Source: https://learn.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-getting-started/aspnet-ajax/understanding-asp-net-ajax-web-services Illustrates the format of the HTTP headers sent when calling a Web Method configured to accept GET requests. ```text GET /CustomerViewer/DemoService.asmx/HttpGetEcho?input=%22Input Value%22 HTTP/1.1 ``` -------------------------------- ### Registering Services in Program.cs (Example 2) Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection Alternative syntax for registering services: Service1 as Scoped, Service2 as Singleton, and Service3 as a Singleton resolved via a factory. ```csharp services.AddScoped(); services.AddSingleton(); var myKey = builder.Configuration["Key"] ?? string.Empty; services.AddSingleton(sp => new Service3(myKey)); ``` -------------------------------- ### Add Initial Migration Setup Source: https://learn.microsoft.com/en-us/aspnet/identity/overview/migrations/migrating-an-existing-website-from-sql-membership-to-aspnet-identity Executes the initial setup code for creating the database schema using C# or VB.NET. ```powershell Add-migration initial ``` -------------------------------- ### Form Tag Helper with GET Method Specified (CSHTML) Source: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search A minimal example showing the Form Tag Helper configured for an HTTP GET request. ```HTML
``` -------------------------------- ### Basic Startup Class Configuration Source: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity This is a minimal example of a Startup class constructor, typically used for dependency injection configuration. ```C# public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } ``` -------------------------------- ### Start OWIN Host and Make HttpClient Request Source: https://learn.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api Starts the OWIN host and demonstrates making a GET request to the Web API using HttpClient. The host is started within a 'using' statement for proper disposal. ```C# using Microsoft.Owin.Hosting; using System; using System.Net.Http; namespace OwinSelfhostSample { public class Program { static void Main() { string baseAddress = "http://localhost:9000/"; // Start OWIN host using (WebApp.Start(url: baseAddress)) { // Create HttpClient and make a request to api/values HttpClient client = new HttpClient(); var response = client.GetAsync(baseAddress + "api/values").Result; Console.WriteLine(response); Console.WriteLine(response.Content.ReadAsStringAsync().Result); Console.ReadLine(); } } } } ``` -------------------------------- ### Set Cached Time on Application Start Source: https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed Cache the current UTC time when the application starts using IDistributedCache. This example demonstrates setting a sliding expiration. ```csharp app.Lifetime.ApplicationStarted.Register(() => { var currentTimeUTC = DateTime.UtcNow.ToString(); byte[] encodedCurrentTimeUTC = System.Text.Encoding.UTF8.GetBytes(currentTimeUTC); var options = new DistributedCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(20)); app.Services.GetService() .Set("cachedTimeUTC", encodedCurrentTimeUTC, options); }); ``` -------------------------------- ### Register ExampleService as Scoped in Startup.cs Source: https://learn.microsoft.com/en-us/aspnet/core/blazor/security Registers the ExampleService as a scoped service within the ConfigureServices method of Startup.cs. This ensures the service has a lifetime tied to the user's circuit. ```csharp services.AddScoped(); ``` -------------------------------- ### Generate GET Request for Books Source: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app This is an example of an HTTP request generated by Endpoints Explorer to fetch all books from the API. It defines the host address and the GET endpoint. ```http @BookStoreApi_HostAddress = https://localhost: GET {{BookStoreApi_HostAddress}}/api/books ``` -------------------------------- ### Example Log Output for GET Request Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-logging Demonstrates the log output for a GET request after applying the SampleHttpLoggingInterceptor. Note the redacted fields and added custom fields. ```log info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1] Request: Path: RedactedPath Accept: RedactedHeader Host: RedactedHeader User-Agent: RedactedHeader Accept-Encoding: RedactedHeader Accept-Language: RedactedHeader Upgrade-Insecure-Requests: RedactedHeader sec-ch-ua: RedactedHeader sec-ch-ua-mobile: RedactedHeader sec-ch-ua-platform: RedactedHeader sec-fetch-site: RedactedHeader sec-fetch-mode: RedactedHeader sec-fetch-user: RedactedHeader sec-fetch-dest: RedactedHeader RequestEnrichment: Stuff Protocol: HTTP/2 Method: GET Scheme: https info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2] Response: Content-Type: RedactedHeader MyResponseHeader: RedactedHeader ResponseEnrichment: Stuff StatusCode: 200 info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[4] ResponseBody: Hello World! ``` -------------------------------- ### Basic Middleware Setup Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware Demonstrates a basic setup of common middleware components in the ASP.NET Core pipeline. ```csharp app.UseAuthorization(); app.UseSession(); app.MapRazorPages(); ``` -------------------------------- ### Program.cs with Custom DI Container (Autofac) Source: https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60 This example demonstrates integrating a custom DI container like Autofac into the minimal hosting model, using `Startup`. ```csharp using Autofac; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Hosting; var builder = WebApplication.CreateBuilder(args); var startup = new Startup(builder.Configuration); startup.ConfigureServices(builder.Services); // Using a custom DI container. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer(startup.ConfigureContainer); var app = builder.Build(); startup.Configure(app, app.Environment); app.Run(); ``` -------------------------------- ### Example API Response: Specific Book Source: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app Shows a JSON object for a single book, retrieved by its ID. This is an example response for the GET /api/books/{id} endpoint. ```JSON { "Id": "61a6058e6c43f32854e51f52", "Name": "Clean Code", "Price": 43.15, "Category": "Computers", "Author": "Robert C. Martin" } ``` -------------------------------- ### Example Project File with .NET Core 3.1 Source: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity Illustrates a sample .NET project file (.csproj) configured for .NET Core 3.1, including necessary ASP.NET Core Identity and Entity Framework Core NuGet package references. ```XML netcoreapp3.1 ``` -------------------------------- ### Start Nginx Service Source: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-apache Start the Nginx service on Ubuntu/Debian-based systems using the systemd init script. This command is typically used after installing Nginx for the first time. ```bash sudo service nginx start ``` -------------------------------- ### DynamicComponent Example 2 Setup Source: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent This code defines the component metadata and event handlers for the DynamicComponent example. It initializes a dictionary of components with their types, names, and initial parameters. ```razor @page "/dynamiccomponent-example-2"

DynamicComponent Component Example 2

@if (selectedComponent is not null) {
} @code { private Dictionary components = new() { [nameof(RocketLabWithWindowSeat)] = new ComponentMetadata() { Type = typeof(RocketLabWithWindowSeat), Name = "Rocket Lab with Window Seat", Parameters = { [nameof(RocketLabWithWindowSeat.WindowSeat)] = false } }, [nameof(VirginGalactic)] = new ComponentMetadata() { Type = typeof(VirginGalactic), Name = "Virgin Galactic" }, [nameof(UnitedLaunchAlliance)] = new ComponentMetadata() { Type = typeof(UnitedLaunchAlliance), Name = "ULA" }, ``` -------------------------------- ### Startup Class with IWebHostEnvironment Injection Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/startup Demonstrates injecting `IWebHostEnvironment` into the `Startup` class constructor, which is available when using the Generic Host. ```csharp public class Startup { private readonly IWebHostEnvironment _env; public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; _env = env; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { if (_env.IsDevelopment()) { } else { } } } ``` -------------------------------- ### Configuring WebHost Directly with Startup Class (Throws Exception) Source: https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60 Shows an attempt to configure `WebHost` directly using `UseStartup()` with `WebApplicationBuilder`. This method is deprecated in .NET 6 and will throw an exception. ```csharp var builder = WebApplication.CreateBuilder(args); try { builder.WebHost.UseStartup(); } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } builder.Services.AddRazorPages(); var app = builder.Build(); ``` -------------------------------- ### Controller Endpoint Details Example Source: https://learn.microsoft.com/en-us/aspnet/core/web-api/http-repl Example output showing the operations available within the 'Fruits' controller, including GET, PUT, and DELETE methods that expect an 'id' parameter. ```console . [get|post] .. [] {id} [get|put|delete] https://localhost:5001/fruits> ``` -------------------------------- ### LibMan Clean Example Source: https://learn.microsoft.com/en-us/aspnet/core/client-side/libman/libman-cli Deletes library files that were previously installed using LibMan. ```bash libman clean ``` -------------------------------- ### Configure Web Host to Use Specific Startup Class Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments Use HostingAbstractionsWebHostBuilderExtensions.UseStartup to specify the assembly name from which to load the correct Startup class based on the current environment. ```csharp public static IHostBuilder CreateHostBuilder(string[] args) { var assemblyName = typeof(Startup).GetTypeInfo().Assembly.FullName; return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(assemblyName); }); } ```