@@ -52,6 +52,7 @@ The below example uses simple, inefficient buffering to transform requests. A mo
5252
5353This sample requires YARP 1.1, see https://github.com/microsoft/reverse-proxy/pull/1569 .
5454
55+ #### Example: Modifying an existing request body
5556``` csharp
5657.AddTransforms (context =>
5758{
@@ -76,6 +77,54 @@ This sample requires YARP 1.1, see https://github.com/microsoft/reverse-proxy/pu
7677});
7778```
7879
80+ ### Important limitations
81+ > ** Custom transforms can only modify a request body if one is already present** in the incoming request.
82+ > They ** cannot add a new body** to a request that originally did not have one (e.g., a POST request with no body or a GET request).
83+ > If you need to add a body where none exists, you must do so in ** middleware that runs before YARP** , not in a transform.
84+
85+ #### Example: Adding a body to a request that did not originally have one
86+ ``` csharp
87+ public class AddRequestBodyMiddleware
88+ {
89+ private readonly RequestDelegate _next ;
90+
91+ public AddRequestBodyMiddleware (RequestDelegate next )
92+ {
93+ _next = next ;
94+ }
95+
96+ public async Task InvokeAsync (HttpContext context )
97+ {
98+ // Only modify specific route and method
99+ if (context .Request .Method == HttpMethods .Post && context .Request .Path == " /my-special-route" )
100+ {
101+ var bodyContent = " key=value" ;
102+ var bodyBytes = Encoding .UTF8 .GetBytes (bodyContent );
103+
104+ // Create a new request body
105+ context .Request .Body = new MemoryStream (bodyBytes );
106+ context .Request .ContentLength = bodyBytes .Length ;
107+
108+ // Replace IHttpRequestBodyDetectionFeature so YARP knows a body is present
109+ context .Features .Set <IHttpRequestBodyDetectionFeature >(new CustomBodyDetectionFeature ());
110+ }
111+
112+ await _next (context );
113+ }
114+
115+ // Helper class to indicate the request can have a body
116+ private class CustomBodyDetectionFeature : IHttpRequestBodyDetectionFeature
117+ {
118+ public bool CanHaveBody => true ;
119+ }
120+ }
121+
122+ ```
123+
124+ #### Note
125+ > You can use ` context.GetRouteModel().Config.RouteId ` in middleware to conditionally apply this logic for specific YARP routes.
126+
127+
79128## Response body transforms
80129
81130YARP does not provide any built in transforms for modifying the response body. However, the body can be modified by custom transforms.
0 commit comments