ASP.NET Core Proxies made easy.
dotnet add package AspNetCore.Proxy
Download the source and run.
dotnet restore
dotnet test src/Test/AspNetCore.Proxy.Tests.csproj
Latest .NET Standard 2.0.
First, you must add the required services.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddProxies();
...
}
You can use the proxy functionality on an existing Controller
by leveraging the Proxy
extension method.
public class MyController : Controller
{
[Route("api/posts/{postId}")]
public Task GetPosts(int postId)
{
return this.ProxyAsync($"https://jsonplaceholder.typicode.com/posts/{postId}");
}
}
You can define a proxy in Configure(IApplicationBuilder app, IHostingEnvironment env)
. The arguments are passed to the underlying lambda as a Dictionary
.
app.UseProxy("api/{arg1}/{arg2}", async (args) => {
// Get the proxied address.
return await SomeCallThatComputesAUrl(args["arg1"], args["arg2"]);
});
You can also make the proxy look and feel almost like a route, but as part of a static method.
First, add the middleware.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseProxies();
...
}
Then, create a static method which returns a Task<string>
or string
(where the string
is the URI to proxy).
[ProxyRoute("api/posts/{arg1}/{arg2}")]
public static async Task<string> GetProxy(string arg1, string arg2)
{
var uri = await SomeCallThatComputesAUrl(arg1, arg2);
return uri;
}
[ProxyRoute("api/comments/{postId}")]
public static async Task<string> GetComments(int postId) => $"https://jsonplaceholder.typicode.com/posts/{postId}";
The MIT License (MIT)
Copyright (c) 2017 Aaron Roney
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.