Giter Site home page Giter Site logo

aspnetcore.proxy's Introduction

AspNetCore.Proxy

Actions Status codecov GitHub Release NuGet Version NuGet Downloads

ASP.NET Core Proxies made easy.

Information

Install

dotnet add package AspNetCore.Proxy

Test

Download the source and run.

dotnet restore
dotnet test src/Test/AspNetCore.Proxy.Tests.csproj

Compatibility

Latest .NET Standard 2.0.

Examples

First, you must add the required services.

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddProxies();
    ...
}

Run a Proxy

You can run a proxy over all endpoints.

app.RunProxy("https://google.com");

In addition, you can route this proxy depending on the context.

app.RunProxy(context =>
{
    if(context.WebSockets.IsWebSocketRequest)
        return "wss://mysite.com/ws";

    return "https://mysite.com";
});

Existing Controller

You can define a proxy over a specific endpoint 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}");
    }
}

In addition, you can proxy to WebSocket endpoints.

public class MyController : Controller
{
    [Route("ws")]
    public Task OpenWs()
    {
        return this.ProxyAsync($"wss://myendpoint.com/ws");
    }
}

You can also pass special options that apply when the proxy operation occurs.

public class MyController : Controller
{
    [Route("api/posts/{postId}")]
    public Task GetPosts(int postId)
    {
        var options = ProxyOptions.Instance
            .WithShouldAddForwardedHeaders(false)
            .WithHttpClientName("MyCustomClient")
            .WithIntercept(async context =>
            {
                if(c.Connection.RemotePort == 7777)
                {
                    c.Response.StatusCode = 300;
                    await c.Response.WriteAsync("I don't like this port, so I am not proxying this request!");
                    return true;
                }

                return false;
            })
            .WithBeforeSend((c, hrm) =>
            {
                // Set something that is needed for the downstream endpoint.
                hrm.Headers.Authorization = new AuthenticationHeaderValue("Basic");

                return Task.CompletedTask;
            })
            .WithAfterReceive((c, hrm) =>
            {
                // Alter the content in  some way before sending back to client.
                var newContent = new StringContent("It's all greek...er, Latin...to me!");
                hrm.Content = newContent;

                return Task.CompletedTask;
            })
            .WithHandleFailure(async (c, e) =>
            {
                // Return a custom error response.
                c.Response.StatusCode = 403;
                await c.Response.WriteAsync("Things borked.");
            });

        return this.ProxyAsync($"https://jsonplaceholder.typicode.com/posts/{postId}", options);
    }
}

Application Builder

You can define a proxy over a specific endpoint 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"]);
});

ProxyRoute Attribute

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}";

License

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.

aspnetcore.proxy's People

Contributors

artur-siwiak avatar bhavishyachandra avatar daniilsokolyuk avatar simonholt avatar twitchax avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.