### LibMan SignalR Client Installation Output Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/signalr.md Example console output confirming the successful download and installation of the SignalR client library. ```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" ``` -------------------------------- ### Minimal API Setup and Basic Endpoints in C# Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/minimal-apis/includes/parameter-binding8-10.md This snippet shows the initial setup for a Minimal API application, including service configuration for an in-memory database and defining basic GET, POST, PUT, and DELETE endpoints. ```csharp using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext(opt => opt.UseInMemoryDatabase("TodoList")); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.MapGet("/todos", GetAllTodos); app.MapGet("/todos/complete", GetCompleteTodos); app.MapGet("/todos/{id}", GetTodo); app.MapPost("/todos", CreateTodo); app.MapPut("/todos/{id}", UpdateTodo); app.MapDelete("/todos/{id}", DeleteTodo); app.Run(); static IResult GetAllTodos(TodoDb db) { return TypedResults.Ok(db.Todos.ToList()); } static IResult GetCompleteTodos(TodoDb db) { return TypedResults.Ok(db.Todos.Where(t => t.IsComplete).ToList()); } ``` -------------------------------- ### Framework Not Found Error Message Example Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/test/troubleshoot-azure-iis.md Example error output when the requested .NET runtime version is not installed on the target machine. Lists all installed versions and the requested version for diagnostic purposes. ```text The specified framework 'Microsoft.NETCore.App', version '3.0.0' was not found. - The following frameworks were found: 2.2.1 at [C:\Program Files\dotnet\x64\shared\Microsoft.NETCore.App] 3.0.0-preview5-27626-15 at [C:\Program Files\dotnet\x64\shared\Microsoft.NETCore.App] 3.0.0-preview6-27713-13 at [C:\Program Files\dotnet\x64\shared\Microsoft.NETCore.App] 3.0.0-preview6-27714-15 at [C:\Program Files\dotnet\x64\shared\Microsoft.NETCore.App] 3.0.0-preview6-27723-08 at [C:\Program Files\dotnet\x64\shared\Microsoft.NETCore.App] ``` -------------------------------- ### Example: Add SSL Certificate for HTTP.sys on Windows Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/servers/httpsys/includes/httpsys8-9.md Concrete example of registering an SSL certificate for `10.0.0.4:443` with a specific certificate hash and application GUID. This demonstrates the `netsh http add sslcert` command in practice. ```console netsh http add sslcert ipport=10.0.0.4:443 certhash=b66ee04419d4ee37464ab8785ff02449980eae10 appid="{00001111-aaaa-2222-bbbb-3333cccc4444}" ``` -------------------------------- ### Start Web Host with URL List Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/host/web-host.md Initialize and start a web host configured to listen on multiple specified URLs using the Start method with a URL array. ```csharp var urls = new List() { "http://*:5000", "http://localhost:5001" }; var host = new WebHostBuilder() .UseKestrel() .UseStartup() .Start(urls.ToArray()); using (host) { Console.ReadLine(); } ``` -------------------------------- ### Basic routing with MapGet endpoint Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/routing/includes/routing3-7.md Demonstrates a minimal routing setup with a single GET endpoint at the root URL. When a GET request is sent to `/`, the response delegate executes and returns 'Hello World!'. Non-matching requests return HTTP 404. ```csharp var builder = WebApplicationBuilder.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run(); ``` -------------------------------- ### Complete Endpoint Configuration for Blazor Integration Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/blazor/components/integration.md This example shows the full 'UseEndpoints' configuration, including default MVC routes, 'MapBlazorHub', and the 'MapFallbackToController' for Blazor routable components. It demonstrates the typical setup in 'Startup.cs'. ```csharp app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapBlazorHub(); endpoints.MapFallbackToController("Blazor", "Home"); }); ``` -------------------------------- ### Basic App Setup for Problem Details Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/error-handling.md Minimal app configuration demonstrating basic setup for problem details handling. ```csharp // Code from Program.cs snippet_apishort // Shows basic app configuration ``` -------------------------------- ### Example: Configure Launch Profile for /CoolApp Path Base Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/blazor/host-and-deploy/app-base-path.md Example configuration for launchSettings.json using /CoolApp as the relative URL path. ```json "commandLineArgs": "--pathbase=/CoolApp", "launchUrl": "CoolApp", ``` -------------------------------- ### Configure Hosting Startup with IHostingStartup and Configuration Priority Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/host/platform-specific-configuration.md This snippet demonstrates implementing IHostingStartup to inject configuration. It shows how to use ConfigureAppConfiguration for higher priority and UseConfiguration for lower priority relative to the app's 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); } } ``` -------------------------------- ### Start Nginx Service Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/host-and-deploy/linux-nginx.md Start the Nginx daemon after installation. Verify the default landing page is accessible at http:///index.nginx-debian.html. ```bash sudo service nginx start ``` -------------------------------- ### Initial Minimal API Setup Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/minimal-apis/includes/parameter-binding7.md Shows the basic setup of a Minimal API application, including endpoint definitions, before refactoring parameters with AsParameters. ```csharp // C# code from Program.cs for snippet_top ``` -------------------------------- ### ASP.NET Core HTTPS certificate installation output Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/security/enforcing-ssl/includes/enforcing-ssl6.md Example output when the .NET Core SDK installs the development certificate during the first-run experience. ```output Installed an ASP.NET Core HTTPS development certificate. To trust the certificate, run 'dotnet dev-certs https --trust' Learn about HTTPS: https://aka.ms/dotnet-https ``` -------------------------------- ### GET Endpoint with Multiple Parameters Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/minimal-apis/includes/parameter-binding7.md An example GET endpoint demonstrating multiple individual parameters before refactoring them into a single type using AsParameters. ```csharp // C# code from Program.cs for snippet_id ``` -------------------------------- ### Run the Sample API Application Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/openapi/openapi-comments.md Navigate to the API directory and execute the application using the .NET CLI. This starts the web server and makes the API accessible locally. ```dotnetcli cd api dotnet run ``` -------------------------------- ### libman install Command Synopsis Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/client-side/libman/libman-cli.md This shows the syntax for installing library files, including options for destination, specific files, and provider. ```console libman install [-d|--destination] [--files] [-p|--provider] [--verbosity] ``` ```console libman install [-h|--help] ``` -------------------------------- ### Send an HTTP Request with a Token Handler (Example) Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/blazor/security/additional-scenarios.md An example of sending an HTTP GET request to a '/weather-forecast' endpoint using an `HttpClient` named 'ExternalApi'. ```csharp using var request = new HttpRequestMessage(HttpMethod.Get, "/weather-forecast"); var client = ClientFactory.CreateClient("ExternalApi"); using var response = await client.SendAsync(request); ``` -------------------------------- ### GET single book by ID with example ID Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/first-mongo-app/includes/first-mongo-app-9.md Concrete example of retrieving a single book by replacing the id variable with an actual MongoDB document ID. ```http @id="61a6058e6c43f32854e51f52" GET {{BookStoreApi_HostAddress}}/api/books/{{id}} ### ``` -------------------------------- ### Basic Authorization with UseAuthorization and [Authorize] Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/migration/22-to-30.md Demonstrates the basic setup of Authorization Middleware in `Startup.Configure` and applying the `[Authorize]` attribute to a controller action to require a signed-in user. ```csharp public void Configure(IApplicationBuilder app) { ... app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } public class HomeController : Controller { [Authorize] public IActionResult BuyWidgets() { ... } } ``` -------------------------------- ### Azure Key Vault configuration example values Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/blazor/security/webassembly/standalone-with-identity/account-confirmation-and-password-recovery.md Example configuration values showing the format for TenantId (Azure tenant GUID) and VaultUri (Key Vault endpoint with trailing slash). ```json "TenantId": "00001111-aaaa-2222-bbbb-3333cccc4444", "VaultUri": "https://contoso.vault.azure.net/" ``` -------------------------------- ### Initialize WebApplication Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/minimal-apis/includes/webapplication8.md Standard initialization using the default template or the direct Create method. ```csharp [!code-csharp[](~/fundamentals/minimal-apis/7.0-samples/WebMinAPIs/Program.cs?name=snippet_default)] ``` ```csharp [!code-csharp[](~/fundamentals/minimal-apis/7.0-samples/WebMinAPIs/Program.cs?name=snippet_create)] ``` -------------------------------- ### JSON Response for Parameterless Get Action Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/first-mongo-app/includes/first-mongo-app3-5.md Example JSON response from GET /api/books endpoint returning a collection of book objects with id, bookName, price, category, and author properties. ```json [ { "id":"5bfd996f7b8e48dc15ff215d", "bookName":"Design Patterns", "price":54.93, "category":"Computers", "author":"Ralph Johnson" }, { "id":"5bfd996f7b8e48dc15ff215e", "bookName":"Clean Code", "price":43.15, "category":"Computers", "author":"Robert C. Martin" } ] ``` -------------------------------- ### Basic routing setup with UseRouting and UseEndpoints Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/routing/includes/routing3-7.md Demonstrates the fundamental routing middleware pipeline registration in Startup.Configure. UseRouting matches requests to endpoints, and UseEndpoints executes the selected endpoint's delegate. ```csharp app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); ``` -------------------------------- ### Chain tasks to Blazor manual start Promise Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/blazor/fundamentals/startup.md Use the Promise returned by Blazor.start() with .then() to execute additional initialization tasks, such as JS interop setup, after Blazor has fully started. ```html ``` -------------------------------- ### Define IStringCache service interface Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/dependency-injection.md Service interface with a Get method for keyed service examples. ```csharp public interface IStringCache { string Get(int key); } ``` -------------------------------- ### Create React App (Legacy, < .NET 11) Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/client-side/dotnet-on-webworkers.md Initialize a new React application using `create-react-app` for earlier .NET versions, then navigate into the project directory. ```bash npx create-react-app react-app ``` ```bash cd react-app ``` -------------------------------- ### GET Single ToDo Item Response (JSON) Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/min-web-api/includes/min-web-api-6-7.md Example JSON response when calling GET /todoitems/{id} for a specific item. If no item matches the ID, a 404 status is returned instead. ```json { "id": 1, "name": "walk dog", "isComplete": true } ``` -------------------------------- ### Configure Services with Simple Injector Container Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/middleware/extensibility-third-party-container.md Startup.ConfigureServices setup that initializes the Simple Injector container, registers the middleware factory and middleware, and makes the database context available for injection. Required for dependency resolution. ```csharp [!code-csharp[](extensibility-third-party-container/samples/3.x/SampleApp/Startup.cs?name=snippet1)] ``` ```csharp [!code-csharp[](extensibility-third-party-container/samples/2.x/SampleApp/Startup.cs?name=snippet1)] ``` -------------------------------- ### JSON Response for Overloaded Get Action with ID Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/first-mongo-app/includes/first-mongo-app3-5.md Example JSON response from GET /api/books/{id} endpoint returning a single book object with id, bookName, price, category, and author properties. ```json { "id":"{ID}", "bookName":"Clean Code", "price":43.15, "category":"Computers", "author":"Robert C. Martin" } ``` -------------------------------- ### Retrieve and Pass Options to Middleware in Startup.cs Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/migration/fx-to-core/areas/http-modules.md Shows how to retrieve configuration values and pass them directly to a middleware instance during application startup. ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... other configuration ... // Direct injection example var options = new MyMiddlewareOptions(); Configuration.GetSection("MyOtherMiddlewareOptionsSection").Bind(options); app.UseMyMiddlewareWithParams(options); // ... other configuration ... } ``` -------------------------------- ### Configure Services and Pipeline Without Startup Class Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/startup/includes/startup56.md Shows how to configure services and the request pipeline using convenience methods on the host builder without a separate Startup class. Multiple ConfigureServices calls append to one another, and the last Configure call is used. ```csharp [!code-csharp[](~/fundamentals/startup/3.0_samples/StartupFilterSample/Program1.cs?name=snippet)] ``` -------------------------------- ### HelloWorldController with Index and Welcome methods Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/first-mvc-app/adding-controller/includes/adding-controller8.md Initial controller with two public methods that return strings as HTTP GET endpoints. The Index method is the default action, and Welcome demonstrates basic action method structure. ```csharp [!code-csharp[](~/tutorials/first-mvc-app/start-mvc/sample/mvcmovie80/Controllers/HelloWorldController.cs?name=snippet_First)] ``` -------------------------------- ### Create Razor Pages Project and Install EF Core Tools Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/data/ef-rp/intro.md CLI commands to create a new Razor Pages project, install the Entity Framework Core tools globally, and apply database migrations for SQLite setup. ```dotnetcli dotnet new webapp -o ContosoUniversity cd ContosoUniversity ``` ```dotnetcli dotnet tool uninstall --global dotnet-ef dotnet tool install --global dotnet-ef --version 5.0.0-* dotnet ef database update ``` -------------------------------- ### Reference hosting startup assembly Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/host/platform-specific-configuration.md Manually reference a bin-deployed hosting startup assembly in the project file for compile-time linking. ```xml .\bin\Debug\netcoreapp2.1\HostingStartupLibrary.dll False ``` -------------------------------- ### Handle GET Request in Privacy Page C# Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/razor-pages/page/includes/page9.md An example of an OnGetAsync method that returns Task without a return statement. ```csharp [!code-csharp[](~/tutorials/razor-pages/razor-pages-start/snapshot_sample9/Pages/Privacy.cshtml.cs)] ``` -------------------------------- ### HttpRepl help output reference Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/web-api/http-repl/index.md Shows the full help documentation displayed by the tool, including setup, HTTP, and navigation commands. ```console Usage: httprepl [] [options] Arguments: - The initial base address for the REPL. Options: -h|--help - Show help information. Once the REPL starts, these commands are valid: Setup Commands: Use these commands to configure the tool for your API server connect Configures the directory structure and base address of the api server set header Sets or clears a header for all requests. e.g. `set header content-type application/json` HTTP Commands: Use these commands to execute requests against your application. GET get - Issues a GET request POST post - Issues a POST request PUT put - Issues a PUT request DELETE delete - Issues a DELETE request PATCH patch - Issues a PATCH request HEAD head - Issues a HEAD request OPTIONS options - Issues a OPTIONS request Navigation Commands: The REPL allows you to navigate your URL space and focus on specific APIs that you are working on. ls Show all endpoints for the current path cd Append the given directory to the currently selected path, or move up a path when using `cd ..` Shell Commands: Use these commands to interact with the REPL shell. clear Removes all text from the shell echo [on/off] Turns request echoing on or off, show the request that was made when using request commands exit Exit the shell REPL Customization Commands: Use these commands to customize the REPL behavior. pref [get/set] Allows viewing or changing preferences, e.g. 'pref set editor.command.default 'C:\\Program Files\\Microsoft VS Code\\Code.exe'` run Runs the script at the given path. A script is a set of commands that can be typed with one command per line ui Displays the Swagger UI page, if available, in the default browser Use `help ` for more detail on an individual command. e.g. `help get`. For detailed tool info, see https://aka.ms/http-repl-doc. ``` -------------------------------- ### Sample App Additional Dependencies File Path Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/host/platform-specific-configuration.md Specific example of the path where the additional dependencies file is placed for the sample application. ```text deployment/additionalDeps/shared/Microsoft.AspNetCore.App/2.1.0/StartupDiagnostics.deps.json ``` -------------------------------- ### LibMan uninstall jQuery examples Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/client-side/libman/libman-cli.md Uninstall jQuery by name alone or with explicit version notation. Both commands succeed when jQuery is installed. ```console libman uninstall jquery ``` ```console libman uninstall jquery@3.3.1 ``` -------------------------------- ### Initialize MongoClient in BookService constructor Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/first-mongo-app/includes/first-mongo-app3-5.md Demonstrates how to retrieve database settings and initialize the MongoClient. ```csharp :::code language="csharp" source="~/tutorials/first-mongo-app/samples/3.x/SampleApp/Services/BookService.cs" id="snippet_BookServiceConstructor" highlight="3"::: ``` -------------------------------- ### Generated HTTP GET Request for Web API Endpoint Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/test/http-files.md This snippet shows an example of an HTTP GET request generated by Endpoints Explorer for a web API endpoint. It targets a weather forecast endpoint and specifies JSON as the accepted response format. ```http GET {{WebApplication1_HostAddress}}/weatherforecast/ Accept: application/json ### ``` -------------------------------- ### GET single book by ID with concrete ID Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/first-mongo-app.md Concrete example of retrieving a single book with an actual ID value substituted into the request. ```http @id="61a6058e6c43f32854e51f52" GET {{BookStoreApi_HostAddress}}/books/{{id}} ### ``` -------------------------------- ### Example VS Code launch.json properties for Blazor WebAssembly Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/blazor/tooling.md An example showing how to set the current working directory to the 'Server' folder, specify a local URL, and configure Google Chrome as the default browser for a Blazor WebAssembly app. ```json "cwd": "${workspaceFolder}/Server", "url": "http://localhost:7268", "browser": "chrome" ``` -------------------------------- ### Typical Recommended Middleware Order in Startup.Configure (ASP.NET Core < 6.0) Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/middleware/index.md This `Startup.Configure` method shows a typical recommended order for adding security-related and other common middleware components in ASP.NET Core applications. ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); // app.UseCookiePolicy(); app.UseRouting(); // app.UseRequestLocalization(); // app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); // app.UseSession(); // app.UseResponseCompression(); // app.UseResponseCaching(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } ``` -------------------------------- ### Invoke gRPC method as JSON Web API Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/grpc/json-transcoding/includes/json-transcoding7.md Example of an HTTP GET request and the corresponding JSON response mapped from a gRPC service. ```http GET /v1/greeter/world ``` ```json { "message": "Hello world" } ``` -------------------------------- ### Fetch OpenAPI Documents by Name (Bash) Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/openapi/aspnetcore-openapi.md Example HTTP GET requests to retrieve OpenAPI documents using their specified names in the URL path. ```bash GET http://localhost:5000/openapi/v1.json GET http://localhost:5000/openapi/internal.json ``` -------------------------------- ### Search Query String URL Example Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/data/ef-rp/sort-filter-page.md Demonstrates how search parameters are appended to the URL when using the HTTP GET method in a Razor Pages form. ```browser-address-bar https://localhost:5001/Students?SearchString=an ``` -------------------------------- ### Display configuration settings on startup for debugging Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/configuration/index.md Enumerate all configuration key-value pairs at app startup using AsEnumerable(). Use compiler directives to limit output to DEBUG builds. ```csharp #if DEBUG foreach (var c in app.Configuration.AsEnumerable()) { Console.WriteLine($"CONFIG: Key: {c.Key} Value: {c.Value}"); } #endif ``` ```csharp #if DEBUG foreach (var c in config.AsEnumerable()) { Console.WriteLine($"CONFIG: Key: {c.Key} Value: {c.Value}"); } #endif ``` -------------------------------- ### Create Generic Host with Startup class (ASP.NET Core < 6.0) Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/host/generic-host.md Creates a .NET Generic Host instance for HTTP workloads using the pre-6.0 hosting model with a Startup class. ```csharp public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); } ``` -------------------------------- ### Database Setup and Scaffolding Commands Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/security/authorization/secure-data.md Install code generation tools, scaffold the Contact model with Razor Pages, and create the initial database migration. ```dotnetcli dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design dotnet tool install -g dotnet-aspnet-codegenerator dotnet-aspnet-codegenerator razorpage -m Contact -udl -dc ApplicationDbContext -outDir Pages\Contacts --referenceScriptLibraries dotnet ef database drop -f dotnet ef migrations add initial dotnet ef database update ``` -------------------------------- ### Event Handler Example 2 in Blazor Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/blazor/components/event-handling.md Demonstrates basic event handling setup in Blazor components across different ASP.NET Core versions. ```razor :::code language="razor" source="~/../blazor-samples/3.1/BlazorSample_WebAssembly/Pages/event-handling/EventHandlerExample2.razor"::: ``` -------------------------------- ### Configure gRPC services in Startup.cs Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/grpc/aspnetcore/includes/aspnetcore3_1.md Register gRPC services and map them to the routing pipeline in the Startup class. ```csharp [!code-csharp[](~/tutorials/grpc/grpc-start/sample/sample3-5/GrpcGreeter/Startup.cs?name=snippet&highlight=7,24)] ``` -------------------------------- ### Initial HelloWorldController Implementation Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/first-mvc-app/adding-controller/includes/adding-controller6.md Define a basic controller with Index and Welcome action methods that return simple string responses. ```csharp [!code-csharp[](~/tutorials/first-mvc-app/start-mvc/sample/MvcMovie60/Controllers/HelloWorldController.cs?name=First)] ``` -------------------------------- ### Get or create cache entry with absolute expiration (C#) Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/performance/caching/memory.md This example shows how to set an absolute expiration time for a cached item, ensuring it is removed after a fixed duration. ```csharp // Code from source file: memory/samples/3.x/WebCacheSample/Controllers/HomeController.cs (snippet99) ``` -------------------------------- ### Trust ASP.NET Core HTTPS Development Certificate Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/security/enforcing-ssl.md Run this command to trust the development certificate on Windows and macOS. This is a one-time setup step required after installing the .NET SDK. ```dotnetcli dotnet dev-certs https --trust ``` -------------------------------- ### HTTP Client and Request Configuration Example Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/servers/yarp/http-client-config.md Complete JSON configuration example showing HttpClient and HttpRequest settings for two clusters with different SSL protocols, connection limits, and version policies. ```json { "Clusters": { "cluster1": { "LoadBalancingPolicy": "Random", "HttpClient": { "SslProtocols": [ "Tls11", "Tls12" ], "MaxConnectionsPerServer": "10", "DangerousAcceptAnyServerCertificate": "true" }, "HttpRequest": { "ActivityTimeout": "00:00:30" }, "Destinations": { "cluster1/destination1": { "Address": "https://localhost:10000/" }, "cluster1/destination2": { "Address": "http://localhost:10010/" } } }, "cluster2": { "HttpClient": { "SslProtocols": [ "Tls12" ] }, "HttpRequest": { "Version": "1.1", "VersionPolicy": "RequestVersionExact" }, "Destinations": { "cluster2/destination1": { "Address": "https://localhost:10001/" } } } } } ``` -------------------------------- ### Configure SignalR HubConnection Timeouts in C# Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/blazor/fundamentals/signalr.md This C# example demonstrates configuring `ServerTimeout`, `KeepAliveInterval`, and `HandshakeTimeout` on a `HubConnectionBuilder` within a Blazor component. These settings are applied before starting the hub connection. ```csharp protected override async Task OnInitializedAsync() { hubConnection = new HubConnectionBuilder() .WithUrl(Navigation.ToAbsoluteUri("/chathub")) .WithServerTimeout(TimeSpan.FromSeconds(30)) .WithKeepAliveInterval(TimeSpan.FromSeconds(15)) .Build(); hubConnection.HandshakeTimeout = TimeSpan.FromSeconds(15); hubConnection.On("ReceiveMessage", (user, message) => ... await hubConnection.StartAsync(); } ``` -------------------------------- ### libman init Command Synopsis Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/client-side/libman/libman-cli.md This shows the syntax for initializing a libman.json file, including options for default destination and provider. ```console libman init [-d|--default-destination] [-p|--default-provider] [--verbosity] ``` ```console libman init [-h|--help] ``` -------------------------------- ### Get or create cache entry synchronously and asynchronously (C#) Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/performance/caching/memory.md This example shows how to use GetOrCreate for synchronous caching and GetOrCreateAsync for asynchronous caching, ensuring an item is added only if it doesn't exist. ```csharp // Code from source file: memory/samples/3.x/WebCacheSample/Controllers/HomeController.cs (snippet2) ``` -------------------------------- ### Build and push backend application Docker image Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/servers/yarp/kubernetes-ingress.md Build the sample backend application and push it to a registry. ```bash docker build . -t {REGISTRY_NAME}/backend:{TAG} docker push {REGISTRY_NAME}/backend:{TAG} ``` -------------------------------- ### Initialize Node.js Project with npm Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/signalr-typescript-webpack/includes/signalr-typescript-webpack6.md Run this command in the project root to create a package.json file. ```console npm init -y ``` -------------------------------- ### Inject and Use IHttpClientFactory for Basic Requests Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/http-requests.md This example shows how to inject `IHttpClientFactory` into a Razor Page model and use it to create an `HttpClient` instance for making a basic HTTP GET request. ```csharp public class BasicUsageModel : PageModel { private readonly IHttpClientFactory _httpClientFactory; public BasicUsageModel(IHttpClientFactory httpClientFactory) => _httpClientFactory = httpClientFactory; public async Task OnGet() { var httpClient = _httpClientFactory.CreateClient(); var response = await httpClient.GetAsync("https://api.github.com/orgs/dotnet/repos"); response.EnsureSuccessStatusCode(); await using var responseStream = await response.Content.ReadAsStreamAsync(); GitHubRepos = await JsonSerializer.DeserializeAsync>(responseStream); } public IEnumerable GitHubRepos { get; set; } } ``` -------------------------------- ### Complete Logging Configuration with All Default Providers Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/logging/index.md Full appsettings.json example showing all default providers (Debug, Console, EventSource) enabled with their respective LogLevel configurations and provider-specific settings like IncludeScopes. ```json { "Logging": { "LogLevel": { // No provider, LogLevel applies to all the enabled providers. "Default": "Error", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Warning" }, "Debug": { // Debug provider. "LogLevel": { "Default": "Information" // Overrides preceding LogLevel:Default setting. } }, "Console": { "IncludeScopes": true, "LogLevel": { "Microsoft.AspNetCore.Mvc.Razor.Internal": "Warning", "Microsoft.AspNetCore.Mvc.Razor.Razor": "Debug", "Microsoft.AspNetCore.Mvc.Razor": "Error", "Default": "Information" } }, "EventSource": { "LogLevel": { "Microsoft": "Information" ``` -------------------------------- ### Local ASP.NET Core Application Run Output Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/tutorials/publish-to-azure-webapp-using-vscode.md This is an example of the console output when an ASP.NET Core application is successfully started using `dotnet run`, showing listening URLs and environment details. ```dotnetcli $ dotnet run Building... info: Microsoft.Hosting.Lifetime[14] Now listening on: https://localhost:7064 info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5119 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0] Content root path: D:\Src\MyMVCapp\ ``` -------------------------------- ### OpenAPI JSON Example for Product Endpoint Source: https://github.com/dotnet/aspnetcore.docs/blob/main/aspnetcore/fundamentals/openapi/includes/api_endpoint_operation.md This JSON snippet illustrates how an API endpoint and its associated operations are structured within an OpenAPI document, showing a GET and PUT operation for a product resource. ```json { "paths": { "/api/products/{id}": { // This is the endpoint "get": { // This is the operation "summary": "Get a product by ID", "parameters": [...], "responses": {...} }, "put": { // Another operation on the same endpoint "summary": "Update a product", "parameters": [...], "responses": {...} } } } } ```