How about creating a reverse proxy with .NET Core or .NET 5?
If you had to do that once, you should know YARP!
YARP is a Reverse Proxy project that Microsoft is working on. For now, it is in preview, but it's an easier way to create a simple reverse proxy for our applications.
How does it work?
In this GitHub, you can find a sample that presents how we can use YARP:
- ProductA: the API that can only list "products".
- ProductB: the API that can only insert new "products"
- Proxy: the reverse proxy that will redirect each request to APIs: ProductA and ProductB.
Basically, what we need to create a simple Reverse Proxy is to set Routes and Clusters in appSettings.json from the Proxy project.
For each Route we should:
- Define how we want to expose an API.
- Set the API original path that Reverse Proxy must redirect our calls.
- Define which Cluster is associated with API.
For Cluster settings, we should define the host address for each API exposed by YARP. When we call a route, YARP will call the original path concatenated with the API address defined in the Cluster section.
See below a sample of YARP settings:
"ReverseProxy": { | |
"Routes": [ | |
{ | |
"RouteId": "produto-v1-listarProduto", | |
"ClusterId": "produto-v1", | |
"Match": { | |
"Path": "/produto", | |
"Methods": [ | |
"GET" | |
] | |
}, | |
"Transforms": [ | |
{ | |
"PathSet": "/v1/product" | |
} | |
] | |
}, | |
{ | |
"RouteId": "produto-v2-incluirProduto", | |
"ClusterId": "produto-v2", | |
"Match": { | |
"Path": "/produto", | |
"Methods": [ | |
"POST" | |
] | |
}, | |
"Transforms": [ | |
{ | |
"PathPattern": "v2/product" | |
} | |
] | |
}, | |
], | |
"Clusters": { | |
"produto-v1": { | |
"Destinations": { | |
"produto-v1-dst": { | |
"Address": "http://localhost:5010" | |
} | |
} | |
}, | |
"produto-v2": { | |
"Destinations": { | |
"produto-v2-dst": { | |
"Address": "http://localhost:5011" | |
} | |
} | |
} | |
} | |
} |
Finally, in our startup class, we need to register YARP and load all settings.
services.AddReverseProxy() | |
.LoadFromConfig(_configuration.GetSection("ReverseProxy")); |
After that, we need to add each route defined in our Proxy appSettings.json to endpoint collections.
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapReverseProxy(); | |
}); |
It's done! Now we can call our APIs through our reverse proxy. Try to get a list of products by this endpoint: http://localhost:5000/produto
As presented above, when we call a route from our Proxy, the request is redirected to the original API, in this case to ProductA API.
Top comments (0)