I want to capture a URL with a parameter and return an external site having the parameter as part of its URL. To simplify, I want this:
/google/<something>
-> https://www.google.com/?q=<something>
How can I achieve this with Yarp?
You can use QueryRouteParameter
: to set the route parameter as a query parameter. Here is an example for your reference:
{
"ReverseProxy": {
"Routes": {
"route1": {
"ClusterId": "cluster1",
"Match": {
"Path": "/WeatherForecast/PP/{**remainder}"
},
"Transforms": [
{
"PathRemovePrefix": "/WeatherForecast/PP"
},
{
"PathSet": "/WeatherForecast/PP/"
},
{
"QueryRouteParameter": "q",
"Set": "remainder"
}
]
}
},
"Clusters": {
"cluster1": {
"Destinations": {
"destination1": {
"Address": "https://localhost:7258"
}
}
}
}
}
}
In this example, I set remainder as a query parameter:https://localhost:7258/WeatherForecast/PP
as my target address.
When I enter
https://localhost:7247/WeatherForecast/PP/3
in the URL
It will jump to my target address:
Update
{
"ReverseProxy": {
"Routes": {
"route1": {
"ClusterId": "cluster1",
"Match": {
"Path": "/google/{**remainder}"
},
"Transforms": [
{
"PathRemovePrefix": "/google"
},
{
"PathSet": "/"
},
{
"QueryRouteParameter": "q",
"Set": "remainder"
}
]
}
},
"Clusters": {
"cluster1": {
"Destinations": {
"destination1": {
"Address": "https://www.google.com/"
}
}
}
}
}
}
When I enter the address https://localhost:7247/google/2
, I will be redirected to https://www.google.com/?q=2