Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions docs/docfx/articles/transforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ Here is an example of common transforms:
"route2" : {
"ClusterId": "cluster1",
"Match": {
"Path": "/api/{plugin}/stuff/{*remainder}"
"Path": "/api/{plugin}/stuff/{**remainder}"
},
"Transforms": [
{ "PathPattern": "/foo/{plugin}/bar/{remainder}" },
{ "PathPattern": "/foo/{plugin}/bar/{**remainder}" },
{
"QueryStringParameter": "q",
"Append": "plugin"
Expand Down Expand Up @@ -235,27 +235,27 @@ This will set the request path with the given value.

Config:
```JSON
{ "PathPattern": "/my/{plugin}/api/{remainder}" }
{ "PathPattern": "/my/{plugin}/api/{**remainder}" }
```
Code:
```csharp
routeConfig = routeConfig.WithTransformPathRouteValues(pattern: new PathString("/my/{plugin}/api/{remainder}"));
routeConfig = routeConfig.WithTransformPathRouteValues(pattern: new PathString("/my/{plugin}/api/{**remainder}"));
```
```C#
transformBuilderContext.AddPathRouteValues(pattern: new PathString("/my/{plugin}/api/{remainder}"));
transformBuilderContext.AddPathRouteValues(pattern: new PathString("/my/{plugin}/api/{**remainder}"));
```

This will set the request path with the given value and replace any `{}` segments with the associated route value. `{}` segments without a matching route value are removed. See ASP.NET Core's [routing docs](https://docs.microsoft.com/aspnet/core/fundamentals/routing#route-template-reference) for more information about route templates.
This will set the request path with the given value and replace any `{}` segments with the associated route value. `{}` segments without a matching route value are removed. The final `{}` segment can be marked as `{**remainder}` to indicate this is a catch-all segment that may contain multiple path segments. See ASP.NET Core's [routing docs](https://docs.microsoft.com/aspnet/core/fundamentals/routing#route-template-reference) for more information about route templates.

Example:

| Step | Value |
|------|-------|
| Route definition | `/api/{plugin}/stuff/{*remainder}` |
| Route definition | `/api/{plugin}/stuff/{**remainder}` |
| Request path | `/api/v1/stuff/more/stuff` |
| Plugin value | `v1` |
| Remainder value | `more/stuff` |
| PathPattern | `/my/{plugin}/api/{remainder}` |
| PathPattern | `/my/{plugin}/api/{**remainder}` |
| Result | `/my/v1/api/more/stuff` |

### QueryValueParameter
Expand Down
22 changes: 16 additions & 6 deletions src/ReverseProxy/Transforms/PathRouteValuesTransform.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.AspNetCore.Routing.Template;

namespace Yarp.ReverseProxy.Transforms
Expand All @@ -24,10 +25,10 @@ public PathRouteValuesTransform(string pattern, TemplateBinderFactory binderFact
{
_ = pattern ?? throw new ArgumentNullException(nameof(pattern));
_binderFactory = binderFactory ?? throw new ArgumentNullException(nameof(binderFactory));
Template = TemplateParser.Parse(pattern);
Pattern = RoutePatternFactory.Parse(pattern);
}

internal RouteTemplate Template { get; }
internal RoutePattern Pattern { get; }

/// <inheritdoc/>
public override ValueTask ApplyAsync(RequestTransformContext context)
Expand All @@ -39,11 +40,20 @@ public override ValueTask ApplyAsync(RequestTransformContext context)

// TemplateBinder.BindValues will modify the RouteValueDictionary
// We make a copy so that the original request is not modified by the transform
var routeValues = new RouteValueDictionary(context.HttpContext.Request.RouteValues);
var routeValues = context.HttpContext.Request.RouteValues;
var routeValuesCopy = new RouteValueDictionary();

// Route values that are not considered defaults will be appended as query parameters. Make them all defaults.
var binder = _binderFactory.Create(Template, defaults: routeValues);
context.Path = binder.BindValues(acceptedValues: routeValues);
// Only copy route values used in the pattern, otherwise they'll be added as query parameters.
foreach (var pattern in Pattern.Parameters)
{
if (routeValues.TryGetValue(pattern.Name, out var value))
{
routeValuesCopy[pattern.Name] = value;
}
}

var binder = _binderFactory.Create(Pattern);
context.Path = binder.BindValues(acceptedValues: routeValuesCopy);

return default;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class PathRouteValuesTransformTests
[InlineData("/{a}/{b}/{c}", "/6/7/8")]
[InlineData("/{a}/foo/{b}/{c}/{d}", "/6/foo/7/8")] // Unknown value (d) dropped
[InlineData("/{a}/foo/{b}", "/6/foo/7")] // Extra values (c) dropped
public async Task Set_PathPattern_ReplacesPathWithRouteValues(string transformValue, string expected)
public async Task ReplacesPatternWithRouteValues(string transformValue, string expected)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
Expand Down Expand Up @@ -45,5 +45,35 @@ public async Task Set_PathPattern_ReplacesPathWithRouteValues(string transformVa
// The transform should not modify the original request's route values
Assert.Equal(routeValues, httpContext.Request.RouteValues);
}

[Fact]
public async Task RouteValuesWithSlashesNotEncoded()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
serviceCollection.AddRouting();
using var services = serviceCollection.BuildServiceProvider();

var routeValues = new Dictionary<string, object>
{
{ "a", "abc" },
{ "b", "def" },
{ "remainder", "klm/nop/qrs" },
};

var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues = new RouteValueDictionary(routeValues);
var context = new RequestTransformContext()
{
Path = "/",
HttpContext = httpContext
};
var transform = new PathRouteValuesTransform("/{a}/{b}/{**remainder}", services.GetRequiredService<TemplateBinderFactory>());
await transform.ApplyAsync(context);
Assert.Equal("/abc/def/klm/nop/qrs", context.Path.Value);

// The transform should not modify the original request's route values
Assert.Equal(routeValues, httpContext.Request.RouteValues);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ private static void ValidatePathRouteValues(TransformBuilderContext builderConte
{
var requestTransform = Assert.Single(builderContext.RequestTransforms);
var pathRouteValuesTransform = Assert.IsType<PathRouteValuesTransform>(requestTransform);
Assert.Equal("/path#", pathRouteValuesTransform.Template.TemplateText);
Assert.Equal("/path#", pathRouteValuesTransform.Pattern.RawText);
}
}
}
8 changes: 2 additions & 6 deletions testassets/ReverseProxy.Config/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@
"ClusterId": "cluster2",
"Match": {
"Hosts": [ "localhost" ],
"Path": "/api/{plugin}/stuff/{*remainder}"
"Path": "/api/{plugin}/stuff/{**remainder}"
},
"Transforms": [
{ "PathPattern": "/foo/{plugin}/bar/{remainder}" },
{ "PathPattern": "/foo/{plugin}/bar/{**remainder}" },
{
"X-Forwarded": "Append",
"HeaderPrefix": "X-Forwarded-"
Expand All @@ -93,10 +93,6 @@
},
{ "ClientCert": "X-Client-Cert" },

{ "PathSet": "/apis" },
{ "PathPrefix": "/apis" },
{ "PathRemovePrefix": "/apis" },

{ "RequestHeadersCopy": "true" },
{ "RequestHeaderOriginalHost": "true" },
{
Expand Down