From 34eef78e16c4aed7f3c5095d23dc5529ccc77792 Mon Sep 17 00:00:00 2001 From: Ben Hopkins Date: Fri, 4 Apr 2025 11:19:15 +0100 Subject: [PATCH 1/2] Fix inconsistent and incorrect code language names --- .../handle-errors/includes/handle-errors7.md | 10 +-- aspnetcore/fundamentals/servers/httpsys.md | 2 +- .../servers/httpsys/includes/httpsys5-7.md | 2 +- .../fundamentals/servers/yarp/authn-authz.md | 2 +- .../fundamentals/servers/yarp/config-files.md | 10 +-- .../servers/yarp/config-filters.md | 4 +- aspnetcore/fundamentals/servers/yarp/cors.md | 2 +- .../servers/yarp/dests-health-checks.md | 24 +++---- .../servers/yarp/diagnosing-yarp-issues.md | 2 +- .../servers/yarp/direct-forwarding.md | 4 +- .../servers/yarp/distributed-tracing.md | 10 +-- .../servers/yarp/header-routing.md | 4 +- .../servers/yarp/http-client-config.md | 30 ++++---- aspnetcore/fundamentals/servers/yarp/http3.md | 2 +- .../fundamentals/servers/yarp/lets-encrypt.md | 6 +- .../servers/yarp/load-balancing.md | 6 +- .../fundamentals/servers/yarp/middleware.md | 12 ++-- .../servers/yarp/output-caching.md | 6 +- .../servers/yarp/queryparameter-routing.md | 4 +- .../servers/yarp/rate-limiting.md | 8 +-- .../servers/yarp/session-affinity.md | 6 +- .../fundamentals/servers/yarp/timeouts.md | 2 +- .../servers/yarp/transforms-request.md | 70 +++++++++---------- .../servers/yarp/transforms-response.md | 32 ++++----- .../fundamentals/servers/yarp/transforms.md | 4 +- aspnetcore/host-and-deploy/iis/http3.md | 4 +- aspnetcore/mvc/controllers/routing.md | 4 +- aspnetcore/performance/caching/hybrid.md | 4 +- aspnetcore/performance/rate-limit.md | 28 ++++---- .../aspnetcore-9/includes/hybrid-cache.md | 2 +- .../data-protection/configuration/overview.md | 2 +- aspnetcore/signalr/configuration.md | 2 +- .../ai-powered-group-chat.md | 2 +- 33 files changed, 156 insertions(+), 156 deletions(-) diff --git a/aspnetcore/fundamentals/minimal-apis/handle-errors/includes/handle-errors7.md b/aspnetcore/fundamentals/minimal-apis/handle-errors/includes/handle-errors7.md index 891f16166f17..9bef32ac6ba6 100644 --- a/aspnetcore/fundamentals/minimal-apis/handle-errors/includes/handle-errors7.md +++ b/aspnetcore/fundamentals/minimal-apis/handle-errors/includes/handle-errors7.md @@ -11,7 +11,7 @@ In a Minimal API app, there are two different built-in centralized mechanisms to This section refers to the following Minimal API app to demonstrate ways to handle exceptions. It throws an exception when the endpoint `/exception` is requested: -``` csharp +```csharp var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); @@ -65,7 +65,7 @@ In non-development environments, use the [Exception Handler Middleware](xref:fun For example, the following code changes the app to respond with an [RFC 7807](https://tools.ietf.org/html/rfc7807)-compliant payload to the client. For more information, see [Problem Details](#problem-details) section. -``` csharp +```csharp var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); @@ -84,7 +84,7 @@ app.Run(); Consider the following Minimal API app. -``` csharp +```csharp var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); @@ -103,7 +103,7 @@ The [`Status Code Pages middleware`](xref:fundamentals/error-handling#sestatusco For example, the following example changes the app to respond with an [RFC 7807](https://tools.ietf.org/html/rfc7807)-compliant payload to the client for all client and server responses, including routing errors (for example, `404 NOT FOUND`). For more information, see the [Problem Details](#problem-details) section. -``` csharp +```csharp var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); @@ -127,7 +127,7 @@ Minimal API apps can be configured to generate problem details response for all The following code configures the app to generate problem details: -``` csharp +```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddProblemDetails(); diff --git a/aspnetcore/fundamentals/servers/httpsys.md b/aspnetcore/fundamentals/servers/httpsys.md index a1ddf2d89cb8..9c9825950233 100644 --- a/aspnetcore/fundamentals/servers/httpsys.md +++ b/aspnetcore/fundamentals/servers/httpsys.md @@ -76,7 +76,7 @@ The preceding Windows 11 Build versions may require the use of a [Windows Inside HTTP/3 is discovered as an upgrade from HTTP/1.1 or HTTP/2 via the `alt-svc` header. That means the first request will normally use HTTP/1.1 or HTTP/2 before switching to HTTP/3. Http.Sys doesn't automatically add the `alt-svc` header, it must be added by the application. The following code is a middleware example that adds the `alt-svc` response header. -```C# +```csharp app.Use((context, next) => { context.Response.Headers.AltSvc = "h3=\":443\""; diff --git a/aspnetcore/fundamentals/servers/httpsys/includes/httpsys5-7.md b/aspnetcore/fundamentals/servers/httpsys/includes/httpsys5-7.md index 16c942550c0a..c42fbb57e529 100644 --- a/aspnetcore/fundamentals/servers/httpsys/includes/httpsys5-7.md +++ b/aspnetcore/fundamentals/servers/httpsys/includes/httpsys5-7.md @@ -60,7 +60,7 @@ The preceding Windows 11 Build versions may require the use of a [Windows Inside HTTP/3 is discovered as an upgrade from HTTP/1.1 or HTTP/2 via the `alt-svc` header. That means the first request will normally use HTTP/1.1 or HTTP/2 before switching to HTTP/3. Http.Sys doesn't automatically add the `alt-svc` header, it must be added by the application. The following code is a middleware example that adds the `alt-svc` response header. -```C# +```csharp app.Use((context, next) => { context.Response.Headers.AltSvc = "h3=\":443\""; diff --git a/aspnetcore/fundamentals/servers/yarp/authn-authz.md b/aspnetcore/fundamentals/servers/yarp/authn-authz.md index ec43faabde22..94f9354b05eb 100644 --- a/aspnetcore/fundamentals/servers/yarp/authn-authz.md +++ b/aspnetcore/fundamentals/servers/yarp/authn-authz.md @@ -23,7 +23,7 @@ No authentication or authorization is performed on requests unless enabled in th Authorization policies can be specified per route via [RouteConfig.AuthorizationPolicy](xref:Yarp.ReverseProxy.Configuration.RouteConfig) and can be bound from the `Routes` sections of the config file. As with other route properties, this can be modified and reloaded without restarting the proxy. Policy names are case insensitive. Example: -```JSON +```json { "ReverseProxy": { "Routes": { diff --git a/aspnetcore/fundamentals/servers/yarp/config-files.md b/aspnetcore/fundamentals/servers/yarp/config-files.md index bcf98675334d..41b4e45150e9 100644 --- a/aspnetcore/fundamentals/servers/yarp/config-files.md +++ b/aspnetcore/fundamentals/servers/yarp/config-files.md @@ -17,7 +17,7 @@ The reverse proxy can load configuration for routes and clusters from files usin ## Loading Configuration To load the proxy configuration from IConfiguration add the following code in Program.cs: -```c# +```csharp using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; @@ -42,13 +42,13 @@ Configuration can be modified during the load sequence using [Configuration Filt ## Multiple Configuration Sources As of 1.1, YARP supports loading the proxy configuration from multiple sources. LoadFromConfig may be called multiple times referencing different IConfiguration sections or may be combine with a different config source like InMemory. Routes can reference clusters from other sources. Note merging partial config from different sources for a given route or cluster is not supported. -```c# +```csharp services.AddReverseProxy() .LoadFromConfig(Configuration.GetSection("ReverseProxy1")) .LoadFromConfig(Configuration.GetSection("ReverseProxy2")); ``` or -```c# +```csharp services.AddReverseProxy() .LoadFromMemory(routes, clusters) @@ -62,7 +62,7 @@ File-based configuration is dynamically mapped to the types in [Yarp.ReverseProx The configuration consists of a named section that you specified above via `Configuration.GetSection("ReverseProxy")`, and contains subsections for routes and clusters. Example: -```JSON +```json { "ReverseProxy": { "Routes": { @@ -105,7 +105,7 @@ The clusters section is an unordered collection of named clusters. A cluster pri For additional fields see [ClusterConfig](xref:Yarp.ReverseProxy.Configuration.ClusterConfig). ## All config properties -```JSON +```json { // Base URLs the server listens on, must be configured independently of the routes below "Urls": "http://localhost:5000;https://localhost:5001", diff --git a/aspnetcore/fundamentals/servers/yarp/config-filters.md b/aspnetcore/fundamentals/servers/yarp/config-filters.md index 8cd1b7ad233d..b6835a4a1f9f 100644 --- a/aspnetcore/fundamentals/servers/yarp/config-filters.md +++ b/aspnetcore/fundamentals/servers/yarp/config-filters.md @@ -25,7 +25,7 @@ Filters can be used for a variety of purposes such as: ## AddConfigFilter Configuration filters are registered in the Dependency Injection system using the [AddConfigFilter](xref:Microsoft.Extensions.DependencyInjection.ReverseProxyServiceCollectionExtensions) API. Any number of unique filters can be added and will be applied in the order added. -```C# +```csharp // Load the configuration and register a config filter services.AddReverseProxy() .LoadFromConfig(_configuration.GetSection("ReverseProxy")) @@ -39,7 +39,7 @@ Filters are called for each route and cluster each time configuration is loaded This example fills in destination addresses from environment variables and sets the route's Order field to 1. -```C# +```csharp using System; using System.Collections.Generic; using System.Text.RegularExpressions; diff --git a/aspnetcore/fundamentals/servers/yarp/cors.md b/aspnetcore/fundamentals/servers/yarp/cors.md index 87f48e993d3c..124f10fdc52f 100644 --- a/aspnetcore/fundamentals/servers/yarp/cors.md +++ b/aspnetcore/fundamentals/servers/yarp/cors.md @@ -23,7 +23,7 @@ The requests won't be automatically matched for cors preflight requests unless e CORS policies can be specified per route via [RouteConfig.CorsPolicy](xref:Yarp.ReverseProxy.Configuration.RouteConfig) and can be bound from the `Routes` sections of the config file. As with other route properties, this can be modified and reloaded without restarting the proxy. Policy names are case insensitive. Example: -```JSON +```json { "ReverseProxy": { "Routes": { diff --git a/aspnetcore/fundamentals/servers/yarp/dests-health-checks.md b/aspnetcore/fundamentals/servers/yarp/dests-health-checks.md index 4dadeb696d00..391fdc0a06f0 100644 --- a/aspnetcore/fundamentals/servers/yarp/dests-health-checks.md +++ b/aspnetcore/fundamentals/servers/yarp/dests-health-checks.md @@ -19,7 +19,7 @@ YARP can proactively monitor destination health by sending periodic probing requ There are several cluster-wide configuration settings controlling active health checks that can be set either in the config file or in code. A dedicated health endpoint can also be specified per destination. #### File example -```JSON +```json "Clusters": { "cluster1": { "HealthCheck": { @@ -49,7 +49,7 @@ There are several cluster-wide configuration settings controlling active health ``` #### Code example -```C# +```csharp var clusters = new[] { new ClusterConfig() @@ -132,7 +132,7 @@ There are 2 main extensibility points in the active health check subsystem. The below is a simple example of a custom `IActiveHealthCheckPolicy` marking destination as `Healthy`, if a successful response code was returned for a probe, and as `Unhealthy` otherwise. -```C# +```csharp public class FirstUnsuccessfulResponseHealthPolicy : IActiveHealthCheckPolicy { private readonly IDestinationHealthUpdater _healthUpdater; @@ -169,13 +169,13 @@ public class FirstUnsuccessfulResponseHealthPolicy : IActiveHealthCheckPolicy The default `IProbingRequestFactory` uses the same `HttpRequest` configuration as proxy requests, to customize that implement your own `IProbingRequestFactory` and register it in DI like the below. -```C# +```csharp services.AddSingleton(); ``` The below is a simple example of a customer `IProbingRequestFactory` concatenating `DestinationConfig.Address` and a fixed health probe path to create the probing request URI. -```C# +```csharp public class CustomProbingRequestFactory : IProbingRequestFactory { public HttpRequestMessage CreateRequest(ClusterConfig clusterConfig, DestinationConfig destinationConfig) @@ -196,7 +196,7 @@ There is one important difference from the active health check logic. Once a des There are several cluster-wide configuration settings controlling passive health checks that can be set either in the config file or in code. #### File example -```JSON +```json "Clusters": { "cluster1": { "HealthCheck": { @@ -222,7 +222,7 @@ There are several cluster-wide configuration settings controlling passive health ``` #### Code example -```C# +```csharp var clusters = new[] { new ClusterConfig() @@ -252,7 +252,7 @@ Passive health check settings are specified on the cluster level in `Cluster/Hea Passive health checks require the `PassiveHealthCheckMiddleware` added into the pipeline for them to work. The default `MapReverseProxy(this IEndpointRouteBuilder endpoints)` method does it automatically, but in case of a manual pipeline construction the [UsePassiveHealthChecks](xref:Microsoft.AspNetCore.Builder.AppBuilderHealthExtensions) method must be called to add that middleware as shown in the example below. -```C# +```csharp endpoints.MapReverseProxy(proxyPipeline => { proxyPipeline.UseAffinitizedDestinationLookup(); @@ -279,7 +279,7 @@ Global parameters are set via the options mechanism using `TransportFailureRateH - `DefaultFailureRateLimit` - default failure rate limit for a destination to be marked as unhealthy that is applied if it's not set on a cluster's metadata. The value is in range `(0,1)`. Default is `0.3` (30%). Global policy options can be set in code as follows: -```C# +```csharp services.Configure(o => { o.DetectionWindowSize = TimeSpan.FromSeconds(30); @@ -318,7 +318,7 @@ There is one main extensibility point in the passive health check subsystem, the The below is a simple example of a custom `IPassiveHealthCheckPolicy` marking destination as `Unhealthy` on the first unsuccessful response to a proxied request. -```C# +```csharp public class FirstUnsuccessfulResponseHealthPolicy : IPassiveHealthCheckPolicy { private static readonly TimeSpan _defaultReactivationPeriod = TimeSpan.FromSeconds(60); @@ -355,7 +355,7 @@ Destinations health state is used to determine which of them are eligible for re ### Configuration #### File example -```JSON +```json "Clusters": { "cluster1": { "HealthCheck": { @@ -377,7 +377,7 @@ Destinations health state is used to determine which of them are eligible for re ``` #### Code example -```C# +```csharp var clusters = new[] { new ClusterConfig() diff --git a/aspnetcore/fundamentals/servers/yarp/diagnosing-yarp-issues.md b/aspnetcore/fundamentals/servers/yarp/diagnosing-yarp-issues.md index ad03d463bb70..92ab44fcfae7 100644 --- a/aspnetcore/fundamentals/servers/yarp/diagnosing-yarp-issues.md +++ b/aspnetcore/fundamentals/servers/yarp/diagnosing-yarp-issues.md @@ -114,7 +114,7 @@ The [Metrics sample](https://github.com/microsoft/reverse-proxy/tree/main/sample To use either of these, create a class implementing a [`Yarp.Telemetry.Consumption` interface](xref:Yarp.Telemetry.Consumption#interfaces), such as : -```C# +```csharp public class ForwarderTelemetry : IForwarderTelemetryConsumer { /// Called before forwarding a request. diff --git a/aspnetcore/fundamentals/servers/yarp/direct-forwarding.md b/aspnetcore/fundamentals/servers/yarp/direct-forwarding.md index 81d7b6f89b90..57fb549bbe73 100644 --- a/aspnetcore/fundamentals/servers/yarp/direct-forwarding.md +++ b/aspnetcore/fundamentals/servers/yarp/direct-forwarding.md @@ -45,7 +45,7 @@ In this example the IHttpForwarder is registered in DI, injected into the endpoi The optional transforms show how to copy all request headers except for the `Host`, it's common that the destination requires its own `Host` from the url. -```C# +```csharp using System; using System.Diagnostics; using System.Net; @@ -136,7 +136,7 @@ internal class CustomTransformer : HttpTransformer There are also [extension methods](xref:Microsoft.AspNetCore.Builder.DirectForwardingIEndpointRouteBuilderExtensions) available that simplify the mapping of IHttpForwarder to endpoints. -```C# +```csharp app.MapForwarder("/{**catch-all}", "https://localhost:10000/", requestConfig, transformer, httpClient); ``` diff --git a/aspnetcore/fundamentals/servers/yarp/distributed-tracing.md b/aspnetcore/fundamentals/servers/yarp/distributed-tracing.md index 457bbef17e68..52667ce794bd 100644 --- a/aspnetcore/fundamentals/servers/yarp/distributed-tracing.md +++ b/aspnetcore/fundamentals/servers/yarp/distributed-tracing.md @@ -32,7 +32,7 @@ For example, to monitor the traces with Application Insights, the proxy applicat `application.csproj`: -``` xml +```xml @@ -40,7 +40,7 @@ For example, to monitor the traces with Application Insights, the proxy applicat `Program.cs`: -``` c# +```csharp using Azure.Monitor.OpenTelemetry.AspNetCore; using OpenTelemetry.Trace; using System.Diagnostics; @@ -70,7 +70,7 @@ app.Run(); ### Example: OpenTelemetry hosting -``` xml +```xml @@ -81,7 +81,7 @@ app.Run(); ``` -``` csharp +```csharp using OpenTelemetry.Logs; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; @@ -136,7 +136,7 @@ YARP will remove any header in [`DistributedContextPropagator.Fields`] so that t If you do not wish the proxy to actively participate in the trace, and wish to keep all the tracing headers as-is, you may do so by setting `SocketsHttpHandler.ActivityHeadersPropagator` to `null`. -```c# +```csharp services.AddReverseProxy() .ConfigureHttpClient((context, handler) => handler.ActivityHeadersPropagator = null); ``` diff --git a/aspnetcore/fundamentals/servers/yarp/header-routing.md b/aspnetcore/fundamentals/servers/yarp/header-routing.md index dca04b65b12e..155dfe06d114 100644 --- a/aspnetcore/fundamentals/servers/yarp/header-routing.md +++ b/aspnetcore/fundamentals/servers/yarp/header-routing.md @@ -33,7 +33,7 @@ Headers are specified in the `Match` section of a proxy route. If multiple headers rules are specified on a route then all must match for a route to be taken. OR logic must be implemented either within a header rule or as separate routes. Configuration: -```JSON +```json "Routes": { "route1" : { "ClusterId": "cluster1", @@ -140,7 +140,7 @@ Configuration: ``` Code: -```C# +```csharp var routes = new[] { new RouteConfig() diff --git a/aspnetcore/fundamentals/servers/yarp/http-client-config.md b/aspnetcore/fundamentals/servers/yarp/http-client-config.md index ca1c05e6ae0a..1fcd85233801 100644 --- a/aspnetcore/fundamentals/servers/yarp/http-client-config.md +++ b/aspnetcore/fundamentals/servers/yarp/http-client-config.md @@ -27,7 +27,7 @@ These types are focused on defining serializable configuration. The code based c HTTP client configuration is based on [HttpClientConfig](xref:Yarp.ReverseProxy.Configuration.HttpClientConfig) and represented by the following configuration schema. If you need a more granular approach, use a [custom implementation](xref:fundamentals/servers/yarp/http-client-config#custom-iforwarderhttpclientfactory) of `IForwarderHttpClientFactory`. -```JSON +```json "HttpClient": { "SslProtocols": [ "" ], "MaxConnectionsPerServer": "", @@ -45,30 +45,30 @@ HTTP client configuration is based on [HttpClientConfig](xref:Yarp.ReverseProxy. Configuration settings: - SslProtocols - [SSL protocols](/dotnet/api/system.security.authentication.sslprotocols) enabled on the given HTTP client. Protocol names are specified as array of strings. Default value is [None](/dotnet/api/system.security.authentication.sslprotocols#System_Security_Authentication_SslProtocols_None). -```JSON +```json "SslProtocols": [ "Tls11", "Tls12" ] ``` - MaxConnectionsPerServer - maximal number of HTTP 1.1 connections open concurrently to the same server. Default value is [int32.MaxValue](/dotnet/api/system.int32.maxvalue). -```JSON +```json "MaxConnectionsPerServer": "10" ``` - DangerousAcceptAnyServerCertificate - indicates whether the server's SSL certificate validity is checked by the client. Setting it to `true` completely disables validation. Default value is `false`. -```JSON +```json "DangerousAcceptAnyServerCertificate": "true" ``` - RequestHeaderEncoding - enables other than ASCII encoding for outgoing request headers. Setting this value will leverage [`SocketsHttpHandler.RequestHeaderEncodingSelector`](/dotnet/api/system.net.http.socketshttphandler.requestheaderencodingselector) and use the selected encoding for all headers. The value is then parsed by [`Encoding.GetEncoding`](/dotnet/api/system.text.encoding.getencoding#System_Text_Encoding_GetEncoding_System_String_), use values like: "utf-8", "iso-8859-1", etc. -```JSON +```json "RequestHeaderEncoding": "utf-8" ``` - ResponseHeaderEncoding - enables other than ASCII encoding for incoming response headers (from requests that the proxy would forward out). Setting this value will leverage [`SocketsHttpHandler.ResponseHeaderEncodingSelector`](/dotnet/api/system.net.http.socketshttphandler.responseheaderencodingselector) and use the selected encoding for all headers. The value is then parsed by [`Encoding.GetEncoding`](/dotnet/api/system.text.encoding.getencoding#System_Text_Encoding_GetEncoding_System_String_), use values like: "utf-8", "iso-8859-1", etc. -```JSON +```json "ResponseHeaderEncoding": "utf-8" ``` Note that if you're using an encoding other than ASCII, you also need to set your server to accept requests and/or send responses with such headers. For example, when using Kestrel as the server, use [`KestrelServerOptions.RequestHeaderEncodingSelector`](/dotnet/api/Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions.RequestHeaderEncodingSelector) / [`.ResponseHeaderEncodingSelector`](/dotnet/api/Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions.ResponseHeaderEncodingSelector) to configure Kestrel to allow `Latin1` ("`iso-8859-1`") headers: -```C# +```csharp var builder = WebApplication.CreateBuilder(args); builder.WebHost.ConfigureKestrel(kestrel => { @@ -78,14 +78,14 @@ builder.WebHost.ConfigureKestrel(kestrel => }); ``` - EnableMultipleHttp2Connections - enables opening additional HTTP/2 connections to the same server when the maximum number of concurrent streams is reached on all existing connections. The default is `true`. See [SocketsHttpHandler.EnableMultipleHttp2Connections](/dotnet/api/system.net.http.socketshttphandler.enablemultiplehttp2connections) -```JSON +```json "EnableMultipleHttp2Connections": false ``` - WebProxy - Enables sending requests through an outbound HTTP proxy to reach the destinations. See [`SocketsHttpHandler.Proxy`](/dotnet/api/system.net.http.socketshttphandler.proxy) for details. - Address - The url address of the outbound proxy. - BypassOnLocal - A bool indicating if requests to local addresses should bypass the outbound proxy. - UseDefaultCredentials - A bool indicating if the current application credentials should be use to authenticate to the outbound proxy. ASP.NET Core does not impersonate authenticated users for outbound requests. -```JSON +```json "WebProxy": { "Address": "http://myproxy:8080", "BypassOnLocal": "true", @@ -95,7 +95,7 @@ builder.WebHost.ConfigureKestrel(kestrel => ### HttpRequest HTTP request configuration is based on [ForwarderRequestConfig](xref:Yarp.ReverseProxy.Forwarder.ForwarderRequestConfig) and represented by the following configuration schema. -```JSON +```json "HttpRequest": { "ActivityTimeout": "", "Version": "", @@ -114,7 +114,7 @@ Configuration settings: ## Configuration example The below example shows 2 samples of HTTP client and request configurations for `cluster1` and `cluster2`. -```JSON +```json { "Clusters": { "cluster1": { @@ -164,7 +164,7 @@ HTTP client configuration uses the type [HttpClientConfig](xref:Yarp.ReverseProx The following is an example of `HttpClientConfig` using [code based](xref:fundamentals/servers/yarp/config-providers) configuration. An instance of `HttpClientConfig` is assigned to the [ClusterConfig.HttpClient](xref:Yarp.ReverseProxy.Configuration.ClusterConfig) property before passing the cluster array to `LoadFromMemory` method. -```C# +```csharp var routes = new[] { new RouteConfig() @@ -198,7 +198,7 @@ services.AddReverseProxy() `ConfigureHttpClient` provides a callback to customize the `SocketsHttpHandler` settings used for proxying requests. This will be called each time a cluster is added or changed. Cluster settings are applied to the handler before the callback. Custom data can be provided in the cluster metadata. This example shows adding a client certificate that will authenticate the proxy to the destination servers. -```C# +```csharp var clientCert = new X509Certificate2("path"); services.AddReverseProxy() .ConfigureHttpClient((context, handler) => @@ -212,7 +212,7 @@ If direct control of HTTP client construction is necessary, the default [IForwar It's recommended that any custom factory set the following `SocketsHttpHandler` properties to the same values as the default factory does in order to preserve a correct reverse proxy behavior and avoid unnecessary overhead. -```C# +```csharp new SocketsHttpHandler { UseProxy = false, @@ -231,7 +231,7 @@ Custom data can be provided in the cluster metadata. The below is an example of a custom `IForwarderHttpClientFactory` implementation. -```C# +```csharp public class CustomForwarderHttpClientFactory : IForwarderHttpClientFactory { public HttpMessageInvoker CreateClient(ForwarderHttpClientContext context) diff --git a/aspnetcore/fundamentals/servers/yarp/http3.md b/aspnetcore/fundamentals/servers/yarp/http3.md index 6862aa4646f2..40922820656d 100644 --- a/aspnetcore/fundamentals/servers/yarp/http3.md +++ b/aspnetcore/fundamentals/servers/yarp/http3.md @@ -20,7 +20,7 @@ YARP 1.1 supports HTTP/3 for inbound and outbound connections using the HTTP/3 s ## Set up HTTP/3 on Kestrel Protocols are required in the listener options: -```C# +```csharp var builder = WebApplication.CreateBuilder(args); builder.WebHost.ConfigureKestrel(kestrel => { diff --git a/aspnetcore/fundamentals/servers/yarp/lets-encrypt.md b/aspnetcore/fundamentals/servers/yarp/lets-encrypt.md index 8328d7ec3e6b..33beeb083d41 100644 --- a/aspnetcore/fundamentals/servers/yarp/lets-encrypt.md +++ b/aspnetcore/fundamentals/servers/yarp/lets-encrypt.md @@ -25,7 +25,7 @@ Add the LettuceEncrypt package dependency: ## Configuration There are required options for LettuceEncrypt that should be set, see the example of `appsettings.json`: -```JSON +```json { "Urls": "http://*:80;https://*:443", @@ -52,7 +52,7 @@ There are required options for LettuceEncrypt that should be set, see the exampl ## Update Services -```C# +```csharp services.AddLettuceEncrypt(); ``` @@ -64,7 +64,7 @@ If your project is explicitly using kestrel options to configure IP addresses, p Example: -```C# +```csharp var builder = WebApplication.CreateBuilder(args); builder.WebHost.ConfigureKestrel(kestrel => { diff --git a/aspnetcore/fundamentals/servers/yarp/load-balancing.md b/aspnetcore/fundamentals/servers/yarp/load-balancing.md index 5b751ad83eaa..20fa54a8c5ce 100644 --- a/aspnetcore/fundamentals/servers/yarp/load-balancing.md +++ b/aspnetcore/fundamentals/servers/yarp/load-balancing.md @@ -33,7 +33,7 @@ If no policy is specified, `PowerOfTwoChoices` will be used. #### File example -```JSON +```json "ReverseProxy": { "Clusters": { "cluster1": { @@ -53,7 +53,7 @@ If no policy is specified, `PowerOfTwoChoices` will be used. #### Code example -```C# +```csharp var clusters = new[] { new ClusterConfig() @@ -100,7 +100,7 @@ Select the destination with the least assigned requests. This requires examining A custom implementation can be provided in DI. -```c# +```csharp // Implement the ILoadBalancingPolicy public sealed class LastLoadBalancingPolicy : ILoadBalancingPolicy { diff --git a/aspnetcore/fundamentals/servers/yarp/middleware.md b/aspnetcore/fundamentals/servers/yarp/middleware.md index 59dc3e3992ce..b1c6d137c21e 100644 --- a/aspnetcore/fundamentals/servers/yarp/middleware.md +++ b/aspnetcore/fundamentals/servers/yarp/middleware.md @@ -19,7 +19,7 @@ ASP.NET Core uses a [middleware pipeline](/aspnet/core/fundamentals/middleware/) ## Defaults The [getting started](xref:fundamentals/servers/yarp/getting-started) sample shows the following Configure method. This sets up a middleware pipeline with development tools, routing, and proxy configured endpoints (`MapReverseProxy`). -```C# +```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddReverseProxy() .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); @@ -59,7 +59,7 @@ Middleware inside the `MapReverseProxy` pipeline have access to all of the proxy The data in `IReverseProxyFeature` are snapshotted from the proxy configuration at the start of the proxy pipeline and will not be affected by proxy configuration changes that occur while the request is being processed. -```C# +```csharp proxyPipeline.Use((context, next) => { var proxyFeature = context.GetReverseProxyFeature(); @@ -78,7 +78,7 @@ Middleware can generate logs, control if a request gets proxied or not, influenc Middleware can inspect request and response fields to generate logs and aggregate metrics. See the note about bodies under "What not to do with middleware" below. -```C# +```csharp proxyPipeline.Use(async (context, next) => { LogRequest(context); @@ -91,7 +91,7 @@ proxyPipeline.Use(async (context, next) => If a middleware inspects a request and determines that it should not be proxied, it may generate its own response and return control to the server without calling `next()`. -```C# +```csharp proxyPipeline.Use((context, next) => { if (!CheckAllowedRequest(context, out var reason)) @@ -114,7 +114,7 @@ Middleware like session affinity and load balancing examine the `IReverseProxyFe `ProxiedDestination` is set by the proxy logic at the end of the pipeline to indicate which destination was ultimately used. If there are no available destinations remaining then a 503 error response is sent. -```C# +```csharp proxyPipeline.Use(async (context, next) => { var proxyFeature = context.GetReverseProxyFeature(); @@ -134,7 +134,7 @@ Middleware can wrap the call to `await next()` in a try/catch block to handle ex The proxy logic at the end of the pipeline ([IHttpForwarder](xref:fundamentals/servers/yarp/direct-forwarding)) does not throw exceptions for common request proxy errors. These are captured and reported in the [IForwarderErrorFeature](xref:Yarp.ReverseProxy.Forwarder.IForwarderErrorFeature) available from `HttpContext.Features` or the `HttpContext.GetForwarderErrorFeature()` extension method. -```C# +```csharp proxyPipeline.Use(async (context, next) => { await next(); diff --git a/aspnetcore/fundamentals/servers/yarp/output-caching.md b/aspnetcore/fundamentals/servers/yarp/output-caching.md index af5c36398ed3..9c0dca219c61 100644 --- a/aspnetcore/fundamentals/servers/yarp/output-caching.md +++ b/aspnetcore/fundamentals/servers/yarp/output-caching.md @@ -25,7 +25,7 @@ No output caching is performed unless enabled in the route or application config Output Cache policies can be specified per route via [RouteConfig.OutputCachePolicy](xref:Yarp.ReverseProxy.Configuration.RouteConfig) and can be bound from the `Routes` sections of the config file. As with other route properties, this can be modified and reloaded without restarting the proxy. Policy names are case insensitive. Example: -```JSON +```json { "ReverseProxy": { "Routes": { @@ -53,7 +53,7 @@ Example: [Output cache policies](/aspnet/core/performance/caching/output) are an ASP.NET Core concept that the proxy utilizes. The proxy provides the above configuration to specify a policy per route and the rest is handled by existing ASP.NET Core output caching middleware. Output cache policies can be configured in Program.cs as follows: -```c# +```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddOutputCache(options => @@ -64,7 +64,7 @@ builder.Services.AddOutputCache(options => Then add the output caching middleware: -```c# +```csharp var app = builder.Build(); app.UseOutputCache(); diff --git a/aspnetcore/fundamentals/servers/yarp/queryparameter-routing.md b/aspnetcore/fundamentals/servers/yarp/queryparameter-routing.md index 530c6b578cf9..13cd2f74f5be 100644 --- a/aspnetcore/fundamentals/servers/yarp/queryparameter-routing.md +++ b/aspnetcore/fundamentals/servers/yarp/queryparameter-routing.md @@ -25,7 +25,7 @@ Query Parameters are specified in the `Match` section of a proxy route. If multiple query parameter rules are specified on a route then all must match for a route to be taken. OR logic must be implemented either within a query parameter rule or as separate routes. Configuration: -```JSON +```json "Routes": { "route1" : { "ClusterId": "cluster1", @@ -120,7 +120,7 @@ Configuration: ``` Code: -```C# +```csharp var routes = new[] { new RouteConfig() diff --git a/aspnetcore/fundamentals/servers/yarp/rate-limiting.md b/aspnetcore/fundamentals/servers/yarp/rate-limiting.md index 14805f7e2b56..203152de189b 100644 --- a/aspnetcore/fundamentals/servers/yarp/rate-limiting.md +++ b/aspnetcore/fundamentals/servers/yarp/rate-limiting.md @@ -22,7 +22,7 @@ The reverse proxy can be used to rate-limit requests before they are proxied to No rate limiting is performed on requests unless enabled in the route or application configuration. However, the Rate Limiting middleware (`app.UseRateLimiter()`) can apply a default limiter applied to all routes, and this doesn't require any opt-in from the config. Example: -```c# +```csharp services.AddRateLimiter(options => options.GlobalLimiter = globalLimiter); ``` @@ -30,7 +30,7 @@ services.AddRateLimiter(options => options.GlobalLimiter = globalLimiter); Rate Limiter policies can be specified per route via [RouteConfig.RateLimiterPolicy](xref:Yarp.ReverseProxy.Configuration.RouteConfig) and can be bound from the `Routes` sections of the config file. As with other route properties, this can be modified and reloaded without restarting the proxy. Policy names are case insensitive. Example: -```JSON +```json { "ReverseProxy": { "Routes": { @@ -58,7 +58,7 @@ Example: [RateLimiter policies](/aspnet/core/performance/rate-limit) are an ASP.NET Core concept that the proxy utilizes. The proxy provides the above configuration to specify a policy per route and the rest is handled by existing ASP.NET Core rate limiting middleware. RateLimiter policies can be configured in services as follows: -```c# +```csharp services.AddRateLimiter(options => { options.AddFixedWindowLimiter("customPolicy", opt => @@ -73,7 +73,7 @@ services.AddRateLimiter(options => Then add the RateLimiter middleware. -```c# +```csharp app.UseRateLimiter(); app.MapReverseProxy(); diff --git a/aspnetcore/fundamentals/servers/yarp/session-affinity.md b/aspnetcore/fundamentals/servers/yarp/session-affinity.md index 46c9021c3619..8c9c05072254 100644 --- a/aspnetcore/fundamentals/servers/yarp/session-affinity.md +++ b/aspnetcore/fundamentals/servers/yarp/session-affinity.md @@ -20,7 +20,7 @@ Session affinity is a mechanism to bind (affinitize) a causally related request Session affinity services are registered in the DI container automatically by `AddReverseProxy()`. The middleware `UseSessionAffinity()` is included by default in the parameterless MapReverseProxy method. If you are customizing the proxy pipeline, place the first middleware **before** adding `UseLoadBalancing()`. Example: -```C# +```csharp app.MapReverseProxy(proxyPipeline => { proxyPipeline.UseSessionAffinity(); @@ -32,7 +32,7 @@ app.MapReverseProxy(proxyPipeline => ### Cluster configuration Session affinity is configured per cluster according to the following configuration scheme. -```JSON +```json "ReverseProxy": { "Clusters": { "": { @@ -59,7 +59,7 @@ Session affinity is configured per cluster according to the following configurat ### Cookie configuration Attributes for configuring the cookie used with the HashCookie, ArrCookie and Cookie policies can be configured using `SessionAffinityCookieConfig`. The properties can be JSON config as show above or in code as shown below: -```C# +```csharp new ClusterConfig { ClusterId = "cluster1", diff --git a/aspnetcore/fundamentals/servers/yarp/timeouts.md b/aspnetcore/fundamentals/servers/yarp/timeouts.md index b9880ca063e4..919d47395cd8 100644 --- a/aspnetcore/fundamentals/servers/yarp/timeouts.md +++ b/aspnetcore/fundamentals/servers/yarp/timeouts.md @@ -27,7 +27,7 @@ Timeouts are specified in a TimeSpan format (HH:MM:SS). Specifying both a Timeou Note that request timeouts do not apply when a debugger is attached to the process. Example: -```JSON +```json { "ReverseProxy": { "Routes": { diff --git a/aspnetcore/fundamentals/servers/yarp/transforms-request.md b/aspnetcore/fundamentals/servers/yarp/transforms-request.md index d4bed2cfd957..861721ff26a4 100644 --- a/aspnetcore/fundamentals/servers/yarp/transforms-request.md +++ b/aspnetcore/fundamentals/servers/yarp/transforms-request.md @@ -31,14 +31,14 @@ The following are built in transforms identified by their primary config key. Th | PathPrefix | A path starting with a '/' | yes | Config: -```JSON +```json { "PathPrefix": "/prefix" } ``` Code: ```csharp routeConfig = routeConfig.WithTransformPathPrefix(prefix: "/prefix"); ``` -```C# +```csharp transformBuilderContext.AddPathPrefix(prefix: "/prefix"); ``` Example:
@@ -55,7 +55,7 @@ This will prefix the request path with the given value. | PathRemovePrefix | A path starting with a '/' | yes | Config: -```JSON +```json { "PathRemovePrefix": "/prefix" } ``` Code: @@ -80,14 +80,14 @@ This will remove the matching prefix from the request path. Matches are made on | PathSet | A path starting with a '/' | yes | Config: -```JSON +```json { "PathSet": "/newpath" } ``` Code: ```csharp routeConfig = routeConfig.WithTransformPathSet(path: "/newpath"); ``` -```C# +```csharp transformBuilderContext.AddPathSet(path: "/newpath"); ``` Example:
@@ -104,14 +104,14 @@ This will set the request path with the given value. | PathPattern | A path template starting with a '/' | yes | Config: -```JSON +```json { "PathPattern": "/my/{plugin}/api/{**remainder}" } ``` Code: ```csharp routeConfig = routeConfig.WithTransformPathRouteValues(pattern: new PathString("/my/{plugin}/api/{**remainder}")); ``` -```C# +```csharp transformBuilderContext.AddPathRouteValues(pattern: new PathString("/my/{plugin}/api/{**remainder}")); ``` @@ -138,7 +138,7 @@ Example: | Set/Append | Static value | yes | Config: -```JSON +```json { "QueryValueParameter": "foo", "Append": "bar" @@ -148,7 +148,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformQueryValue(queryKey: "foo", value: "bar", append: true); ``` -```C# +```csharp transformBuilderContext.AddQueryValue(queryKey: "foo", value: "bar", append: true); ``` @@ -173,7 +173,7 @@ Example: | Set/Append | The name of a route value | yes | Config: -```JSON +```json { "QueryRouteParameter": "foo", "Append": "remainder" @@ -183,7 +183,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformQueryRouteValue(queryKey: "foo", routeValueKey: "remainder", append: true); ``` -```C# +```csharp transformBuilderContext.AddQueryRouteValue(queryKey: "foo", routeValueKey: "remainder", append: true); ``` @@ -209,14 +209,14 @@ Example: | QueryRemoveParameter | Name of a query string parameter | yes | Config: -```JSON +```json { "QueryRemoveParameter": "foo" } ``` Code: ```csharp routeConfig = routeConfig.WithTransformQueryRemoveKey(queryKey: "foo"); ``` -```C# +```csharp transformBuilderContext.AddQueryRemoveKey(queryKey: "foo"); ``` @@ -240,7 +240,7 @@ Example: | Set | The new http method | yes | Config: -```JSON +```json { "HttpMethodChange": "PUT", "Set": "POST" @@ -250,7 +250,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformHttpMethodChange(fromHttpMethod: HttpMethods.Put, toHttpMethod: HttpMethods.Post); ``` -```C# +```csharp transformBuilderContext.AddHttpMethodChange(fromHttpMethod: HttpMethods.Put, toHttpMethod: HttpMethods.Post); ``` @@ -265,14 +265,14 @@ This will change PUT requests to POST. | RequestHeadersCopy | true/false | true | yes | Config: -```JSON +```json { "RequestHeadersCopy": "false" } ``` Code: ```csharp routeConfig = routeConfig.WithTransformCopyRequestHeaders(copy: false); ``` -```C# +```csharp transformBuilderContext.CopyRequestHeaders = false; ``` @@ -287,13 +287,13 @@ This sets if all incoming request headers are copied to the proxy request. This | RequestHeaderOriginalHost | true/false | false | yes | Config: -```JSON +```json { "RequestHeaderOriginalHost": "true" } ``` ```csharp routeConfig = routeConfig.WithTransformUseOriginalHostHeader(useOriginal: true); ``` -```C# +```csharp transformBuilderContext.AddOriginalHost(true); ``` @@ -309,7 +309,7 @@ This specifies if the incoming request Host header should be copied to the proxy | Set/Append | The header value | yes | Config: -```JSON +```json { "RequestHeader": "MyHeader", "Set": "MyValue" @@ -319,7 +319,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformRequestHeader(headerName: "MyHeader", value: "MyValue", append: false); ``` -```C# +```csharp transformBuilderContext.AddRequestHeader(headerName: "MyHeader", value: "MyValue", append: false); ``` @@ -341,7 +341,7 @@ Note: setting "" as a header value is not recommended and can cause an undefined | Set/Append | The name of a route value | yes | Config: -```JSON +```json { "RequestHeaderRouteValue": "MyHeader", "Set": "MyRouteKey" @@ -351,7 +351,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformRequestHeaderRouteValue(headerName: "MyHeader", routeValueKey: "key", append: false); ``` -```C# +```csharp transformBuilderContext.AddRequestHeaderRouteValue(headerName: "MyHeader", routeValueKey: "key", append: false); ``` @@ -378,7 +378,7 @@ Note: setting "" as a header value is not recommended and can cause an undefined | RequestHeaderRemove | The header name | yes | Config: -```JSON +```json { "RequestHeaderRemove": "MyHeader" } @@ -387,7 +387,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformRequestHeaderRemove(headerName: "MyHeader"); ``` -```C# +```csharp transformBuilderContext.AddRequestHeaderRemove(headerName: "MyHeader"); ``` @@ -406,7 +406,7 @@ This removes the named header. | RequestHeadersAllowed | A semicolon separated list of allowed header names. | yes | Config: -```JSON +```json { "RequestHeadersAllowed": "Header1;header2" } @@ -415,7 +415,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformRequestHeadersAllowed("Header1", "header2"); ``` -```C# +```csharp transformBuilderContext.AddRequestHeadersAllowed("Header1", "header2"); ``` @@ -448,7 +448,7 @@ Only header1 and header2 are copied to the proxy request. Action "Off" completely disables the transform. Config: -```JSON +```json { "X-Forwarded": "Set", "For": "Remove", @@ -467,7 +467,7 @@ routeConfig = routeConfig.WithTransformXForwarded( ForwardedTransformActions? xProto = null, ForwardedTransformActions? xPrefix = null); ``` -```C# +```csharp transformBuilderContext.AddXForwarded(ForwardedTransformActions.Set); transformBuilderContext.AddXForwardedFor(headerName: "X-Forwarded-For", ForwardedTransformActions.Append); transformBuilderContext.AddXForwardedHost(headerName: "X-Forwarded-Host", ForwardedTransformActions.Append); @@ -483,10 +483,10 @@ X-Forwarded-Host: IncomingHost:5000 X-Forwarded-Prefix: /path/base ``` Disable default headers: -```JSON +```json { "X-Forwarded": "Off" } ``` -```C# +```csharp transformBuilderContext.UseDefaultForwarders = false; ``` @@ -521,7 +521,7 @@ The {Prefix}Prefix header value is taken from `HttpContext.Request.PathBase`. Th | Action | Action to apply to this header (Set, Append, Remove, Off) | Set | no | Config: -```JSON +```json { "Forwarded": "by,for,host,proto", "ByFormat": "Random", @@ -533,7 +533,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformForwarded(useHost: true, useProto: true, forFormat: NodeFormat.IpAndPort, ByFormat: NodeFormat.Random, action: ForwardedTransformAction.Append); ``` -```C# +```csharp transformBuilderContext.AddForwarded(useHost: true, useProto: true, forFormat: NodeFormat.IpAndPort, ByFormat: NodeFormat.Random, action: ForwardedTransformAction.Append); ``` Example: @@ -580,14 +580,14 @@ The RFC allows a [variety of formats](https://tools.ietf.org/html/rfc7239#sectio | ClientCert | The header name | yes | Config: -```JSON +```json { "ClientCert": "X-Client-Cert" } ``` Code: ```csharp routeConfig = routeConfig.WithTransformClientCertHeader(headerName: "X-Client-Cert"); ``` -```C# +```csharp transformBuilderContext.AddClientCertHeader(headerName: "X-Client-Cert"); ``` Example: diff --git a/aspnetcore/fundamentals/servers/yarp/transforms-response.md b/aspnetcore/fundamentals/servers/yarp/transforms-response.md index 709aad158312..3ba228a22eec 100644 --- a/aspnetcore/fundamentals/servers/yarp/transforms-response.md +++ b/aspnetcore/fundamentals/servers/yarp/transforms-response.md @@ -25,14 +25,14 @@ In code these are implemented as derivations of the abstract classes [ResponseTr | ResponseHeadersCopy | true/false | true | yes | Config: -```JSON +```json { "ResponseHeadersCopy": "false" } ``` Code: ```csharp routeConfig = routeConfig.WithTransformCopyResponseHeaders(copy: false); ``` -```C# +```csharp transformBuilderContext.CopyResponseHeaders = false; ``` @@ -49,7 +49,7 @@ This sets if all proxy response headers are copied to the client response. This | When | Success/Always/Failure | Success | no | Config: -```JSON +```json { "ResponseHeader": "HeaderName", "Append": "value", @@ -60,7 +60,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformResponseHeader(headerName: "HeaderName", value: "value", append: true, ResponseCondition.Success); ``` -```C# +```csharp transformBuilderContext.AddResponseHeader(headerName: "HeaderName", value: "value", append: true, always: ResponseCondition.Success); ``` Example: @@ -83,7 +83,7 @@ Note: setting "" as a header value is not recommended and can cause an undefined | When | Success/Always/Failure | Success | no | Config: -```JSON +```json { "ResponseHeaderRemove": "HeaderName", "When": "Success" @@ -93,7 +93,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformResponseHeaderRemove(headerName: "HeaderName", ResponseCondition.Success); ``` -```C# +```csharp transformBuilderContext.AddResponseHeaderRemove(headerName: "HeaderName", ResponseCondition.Success); ``` Example: @@ -113,7 +113,7 @@ This removes the named response header. | ResponseHeadersAllowed | A semicolon separated list of allowed header names. | yes | Config: -```JSON +```json { "ResponseHeadersAllowed": "Header1;header2" } @@ -122,7 +122,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformResponseHeadersAllowed("Header1", "header2"); ``` -```C# +```csharp transformBuilderContext.AddResponseHeadersAllowed("Header1", "header2"); ``` @@ -148,14 +148,14 @@ Only header1 and header2 are copied from the proxy response. | ResponseTrailersCopy | true/false | true | yes | Config: -```JSON +```json { "ResponseTrailersCopy": "false" } ``` Code: ```csharp routeConfig = routeConfig.WithTransformCopyResponseTrailers(copy: false); ``` -```C# +```csharp transformBuilderContext.CopyResponseTrailers = false; ``` @@ -172,7 +172,7 @@ This sets if all proxy response trailers are copied to the client response. This | When | Success/Always/Failure | Success | no | Config: -```JSON +```json { "ResponseTrailer": "HeaderName", "Append": "value", @@ -183,7 +183,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformResponseTrailer(headerName: "HeaderName", value: "value", append: true, ResponseCondition.Success); ``` -```C# +```csharp transformBuilderContext.AddResponseTrailer(headerName: "HeaderName", value: "value", append: true, ResponseCondition.Success); ``` Example: @@ -205,7 +205,7 @@ ResponseTrailer follows the same structure and guidance as [ResponseHeader](xref | When | Success/Always/Failure | Success | no | Config: -```JSON +```json { "ResponseTrailerRemove": "HeaderName", "When": "Success" @@ -215,7 +215,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformResponseTrailerRemove(headerName: "HeaderName", ResponseCondition.Success); ``` -```C# +```csharp transformBuilderContext.AddResponseTrailerRemove(headerName: "HeaderName", ResponseCondition.Success); ``` Example: @@ -235,7 +235,7 @@ ResponseTrailerRemove follows the same structure and guidance as [ResponseHeader | ResponseTrailersAllowed | A semicolon separated list of allowed header names. | yes | Config: -```JSON +```json { "ResponseTrailersAllowed": "Header1;header2" } @@ -244,7 +244,7 @@ Code: ```csharp routeConfig = routeConfig.WithTransformResponseTrailersAllowed("Header1", "header2"); ``` -```C# +```csharp transformBuilderContext.AddResponseTrailersAllowed("Header1", "header2"); ``` diff --git a/aspnetcore/fundamentals/servers/yarp/transforms.md b/aspnetcore/fundamentals/servers/yarp/transforms.md index cbeae5a4b269..8365a7cde13d 100644 --- a/aspnetcore/fundamentals/servers/yarp/transforms.md +++ b/aspnetcore/fundamentals/servers/yarp/transforms.md @@ -58,7 +58,7 @@ Transforms can be added to routes either through configuration or programmatical Transforms can be configured on [RouteConfig.Transforms](xref:Yarp.ReverseProxy.Configuration.RouteConfig) and can be bound from the `Routes` sections of the config file. These can be modified and reloaded without restarting the proxy. A transform is configured using one or more key-value string pairs. Here is an example of common transforms: -```JSON +```json { "ReverseProxy": { "Routes": { @@ -130,7 +130,7 @@ The `AddTransforms` callback provides a [TransformBuilderContext](xref:Yarp.Reve The `TransformBuilderContext` also includes an `IServiceProvider` for access to any needed services. -```C# +```csharp services.AddReverseProxy() .LoadFromConfig(_configuration.GetSection("ReverseProxy")) .AddTransforms(builderContext => diff --git a/aspnetcore/host-and-deploy/iis/http3.md b/aspnetcore/host-and-deploy/iis/http3.md index 56f1c4db8520..f724f5ad10f7 100644 --- a/aspnetcore/host-and-deploy/iis/http3.md +++ b/aspnetcore/host-and-deploy/iis/http3.md @@ -37,7 +37,7 @@ For an in-process deployment when an HTTP/3 connection is established, [`HttpReq HTTP/3 is discovered as an upgrade from HTTP/1.1 or HTTP/2 via the [`alt-svc`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Alt-Svc) header. That means the first request will normally use HTTP/1.1 or HTTP/2 before switching to HTTP/3. IIS doesn't automatically add the `alt-svc` header, it must be added by the application. The following code is a middleware example that adds the `alt-svc` response header. -```C# +```csharp app.Use((context, next) => { context.Response.Headers.AltSvc = "h3=\":443\""; @@ -72,7 +72,7 @@ For an in-process deployment when an HTTP/3 connection is established, [`HttpReq HTTP/3 is discovered as an upgrade from HTTP/1.1 or HTTP/2 via the `alt-svc` header. That means the first request will normally use HTTP/1.1 or HTTP/2 before switching to HTTP/3. IIS doesn't automatically add the `alt-svc` header, it must be added by the application. The following code is a middleware example that adds the `alt-svc` response header. -```C# +```csharp app.Use((context, next) => { context.Response.Headers.AltSvc = "h3=\":443\""; diff --git a/aspnetcore/mvc/controllers/routing.md b/aspnetcore/mvc/controllers/routing.md index afbb22e2947a..98c2a9428329 100644 --- a/aspnetcore/mvc/controllers/routing.md +++ b/aspnetcore/mvc/controllers/routing.md @@ -661,7 +661,7 @@ If the app is using the default conventional route, the value of the `url` varia * The route values from the current request, which are called **ambient values**. * The values passed to `Url.Action` and substituting those values into the route template: -``` text +```text ambient values: { controller = "UrlGeneration", action = "Source" } values passed to Url.Action: { controller = "UrlGeneration", action = "Destination" } route template: {controller}/{action}/{id?} @@ -1501,7 +1501,7 @@ If the app is using the default conventional route, the value of the `url` varia * The route values from the current request, which are called **ambient values**. * The values passed to `Url.Action` and substituting those values into the route template: -``` text +```text ambient values: { controller = "UrlGeneration", action = "Source" } values passed to Url.Action: { controller = "UrlGeneration", action = "Destination" } route template: {controller}/{action}/{id?} diff --git a/aspnetcore/performance/caching/hybrid.md b/aspnetcore/performance/caching/hybrid.md index ef7131920b2c..c880d5c7c31c 100644 --- a/aspnetcore/performance/caching/hybrid.md +++ b/aspnetcore/performance/caching/hybrid.md @@ -53,13 +53,13 @@ The `key` passed to `GetOrCreateAsync` must uniquely identify the data being cac Both types of uniqueness are usually ensured by using string concatenation to make a single key string composed of different parts concatenated into one string. For example: -```c# +```csharp cache.GetOrCreateAsync($"/orders/{region}/{orderId}", ...); ``` or -```c# +```csharp cache.GetOrCreateAsync($"user_prefs_{userId}", ...); ``` diff --git a/aspnetcore/performance/rate-limit.md b/aspnetcore/performance/rate-limit.md index 8ed7cc681dc4..c63dd5fb1b64 100644 --- a/aspnetcore/performance/rate-limit.md +++ b/aspnetcore/performance/rate-limit.md @@ -56,7 +56,7 @@ The following steps show how to use the rate limiting middleware in an ASP.NET C In the `Program.cs` file, configure the rate limiting services by adding the appropriate rate limiting policies. Policies can either be defined as global or named polices. The following example permits 10 requests per minute by user (identity) or globally: - ``` csharp + ```csharp builder.Services.AddRateLimiter(options => { options.GlobalLimiter = PartitionedRateLimiter.Create(httpContext => @@ -74,7 +74,7 @@ The following steps show how to use the rate limiting middleware in an ASP.NET C Named polices need to be explicitly applied to the pages or endpoints. The following example adds a fixed window limiter policy named `"fixed"` which we'll add to an endpoint later: - ``` csharp + ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddRateLimiter(options => @@ -97,7 +97,7 @@ The following steps show how to use the rate limiting middleware in an ASP.NET C In the `Program.cs` file, enable the rate limiting middleware by calling [UseRateLimiter](/dotnet/api/microsoft.aspnetcore.builder.ratelimiterapplicationbuilderextensions.useratelimiter): - ``` csharp + ```csharp app.UseRouting(); app.UseRateLimiter(); @@ -116,7 +116,7 @@ The following steps show how to use the rate limiting middleware in an ASP.NET C Apply a named policy to the endpoint or group, for example: -``` csharp +```csharp app.MapGet("/api/resource", () => "This endpoint is rate limited") .RequireRateLimiting("fixed"); // Apply specific policy to an endpoint @@ -127,7 +127,7 @@ app.MapGet("/api/resource", () => "This endpoint is rate limited") Apply the configured rate limiting policies to specific endpoints or globally. For example, to apply the "fixed" policy to all controller endpoints: -``` csharp +```csharp app.UseEndpoints(endpoints => { endpoints.MapControllers().RequireRateLimiting("fixed"); @@ -139,7 +139,7 @@ app.UseEndpoints(endpoints => To set rate limiting for all of the app's routable Razor components, specify with the rate limiting policy name on the call in the `Program` file. In the following example, the rate limiting policy named "`policy`" is applied: -``` csharp +```csharp app.MapRazorComponents() .AddInteractiveServerRenderMode() .RequireRateLimiting("policy"); @@ -147,7 +147,7 @@ app.MapRazorComponents() To set a policy for a single routable Razor component or a folder of components via an `_Imports.razor` file, the [`[EnableRateLimiting]` attribute](xref:Microsoft.AspNetCore.RateLimiting.EnableRateLimitingAttribute) is applied with the policy name. In the following example, the rate limiting policy named "`override`" is applied. The policy replaces any policies currently applied to the endpoint. The global limiter still runs on the endpoint with this attribute applied. -``` blazor +```blazor @page "/counter" @using Microsoft.AspNetCore.RateLimiting @attribute [EnableRateLimiting("override")] @@ -290,7 +290,7 @@ Partitioned rate limiting gives you fine-grained control over how you manage API ### By IP Address -``` csharp +```csharp options.GlobalLimiter = PartitionedRateLimiter.Create(httpContext => RateLimitPartition.GetFixedWindowLimiter( partitionKey: httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown", @@ -302,7 +302,7 @@ options.GlobalLimiter = PartitionedRateLimiter.Create(httpC ``` ### By User Identity -``` csharp +```csharp options.GlobalLimiter = PartitionedRateLimiter.Create(httpContext => RateLimitPartition.GetFixedWindowLimiter( partitionKey: httpContext.User.Identity?.Name ?? "anonymous", @@ -314,7 +314,7 @@ options.GlobalLimiter = PartitionedRateLimiter.Create(httpC ``` ### By API Key -``` csharp +```csharp options.GlobalLimiter = PartitionedRateLimiter.Create(httpContext => { string apiKey = httpContext.Request.Headers["X-API-Key"].ToString() ?? "no-key"; @@ -343,7 +343,7 @@ options.GlobalLimiter = PartitionedRateLimiter.Create(httpC ### By Endpoint Path -``` csharp +```csharp options.GlobalLimiter = PartitionedRateLimiter.Create(httpContext => { string path = httpContext.Request.Path.ToString(); @@ -384,7 +384,7 @@ For more information, see the [CreateChained source code](https://github.com/dot For simple cases, you can just set the status code: -``` csharp +```csharp builder.Services.AddRateLimiter(options => { // Set a custom status code for rejections @@ -396,7 +396,7 @@ builder.Services.AddRateLimiter(options => The most common approach is to register an OnRejected callback when configuring rate limiting: -``` csharp +```csharp builder.Services.AddRateLimiter(options => { // Rate limiter configuration... @@ -421,7 +421,7 @@ Another option is to queue the request: With queuing enabled, when a request exceeds the rate limit, it's placed in a queue where the request waits until a permit becomes available or until a timeout occurs. Requests are processed according to a configurable queue order. -``` csharp +```csharp builder.Services.AddRateLimiter(options => { options.AddFixedWindowLimiter("api", options => diff --git a/aspnetcore/release-notes/aspnetcore-9/includes/hybrid-cache.md b/aspnetcore/release-notes/aspnetcore-9/includes/hybrid-cache.md index f78bd494f1df..490cc665d18d 100644 --- a/aspnetcore/release-notes/aspnetcore-9/includes/hybrid-cache.md +++ b/aspnetcore/release-notes/aspnetcore-9/includes/hybrid-cache.md @@ -55,7 +55,7 @@ That's a lot of work to get right each time, including things like serialization To simplify and improve this code with `HybridCache`, we first need to add the new library `Microsoft.Extensions.Caching.Hybrid`: -``` xml +```xml ``` diff --git a/aspnetcore/security/data-protection/configuration/overview.md b/aspnetcore/security/data-protection/configuration/overview.md index cd399865c2ff..d42b85891ff9 100644 --- a/aspnetcore/security/data-protection/configuration/overview.md +++ b/aspnetcore/security/data-protection/configuration/overview.md @@ -284,7 +284,7 @@ Sign in to Azure using the CLI, for example: ```azurecli az login -``` +``` To store keys in [Azure Key Vault](https://azure.microsoft.com/services/key-vault/), configure the system with in the `Startup` class. `blobUriWithSasToken` is the full URI where the key file should be stored. The URI must contain the SAS token as a query string parameter: diff --git a/aspnetcore/signalr/configuration.md b/aspnetcore/signalr/configuration.md index 7ce850ea32ad..b272b6e3d7ba 100644 --- a/aspnetcore/signalr/configuration.md +++ b/aspnetcore/signalr/configuration.md @@ -290,7 +290,7 @@ In the .NET Client, timeout values are specified as `TimeSpan` values. The following example shows values that are double the default values: -```C# +```csharp var builder = new HubConnectionBuilder() .WithUrl(Navigation.ToAbsoluteUri("/chathub")) .WithServerTimeout(TimeSpan.FromSeconds(60)) diff --git a/aspnetcore/tutorials/ai-powered-group-chat/ai-powered-group-chat.md b/aspnetcore/tutorials/ai-powered-group-chat/ai-powered-group-chat.md index c98af7b7c252..e96d89dadb5f 100644 --- a/aspnetcore/tutorials/ai-powered-group-chat/ai-powered-group-chat.md +++ b/aspnetcore/tutorials/ai-powered-group-chat/ai-powered-group-chat.md @@ -135,7 +135,7 @@ if (totalCompletion.Length - lastSentTokenLength > 20) lastSentTokenLength = totalCompletion.Length; } -``` +``` ## Explore further From afadf213e2385cad9441b75817be335148919f23 Mon Sep 17 00:00:00 2001 From: Luke Latham <1622880+guardrex@users.noreply.github.com> Date: Fri, 4 Apr 2025 07:37:07 -0400 Subject: [PATCH 2/2] Update aspnetcore/performance/rate-limit.md --- aspnetcore/performance/rate-limit.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aspnetcore/performance/rate-limit.md b/aspnetcore/performance/rate-limit.md index c63dd5fb1b64..e7347659ab39 100644 --- a/aspnetcore/performance/rate-limit.md +++ b/aspnetcore/performance/rate-limit.md @@ -147,7 +147,7 @@ app.MapRazorComponents() To set a policy for a single routable Razor component or a folder of components via an `_Imports.razor` file, the [`[EnableRateLimiting]` attribute](xref:Microsoft.AspNetCore.RateLimiting.EnableRateLimitingAttribute) is applied with the policy name. In the following example, the rate limiting policy named "`override`" is applied. The policy replaces any policies currently applied to the endpoint. The global limiter still runs on the endpoint with this attribute applied. -```blazor +```razor @page "/counter" @using Microsoft.AspNetCore.RateLimiting @attribute [EnableRateLimiting("override")]