twitchax / AspNetCore.Proxy

ASP.NET Core Proxies made easy.
MIT License
525 stars 83 forks source link

Add proxy options. #23

Closed twitchax closed 5 years ago

twitchax commented 5 years ago

Allow the developer to set proxy options.

public class MyController : Controller
{
    [Route("api/posts/{postId}")]
    public Task GetPosts(int postId)
    {
        var options = ProxyOptions.Instance
            .WithShouldAddForwardedHeaders(false)
            .WithBeforeSend((c, hrm) =>
            {
                // Set something that is needed for the downstream endpoint.
                hrm.Headers.Authorization = new AuthenticationHeaderValue("Basic");
            })
            .WithAfterReceive((c, hrm) =>
            {
                // Alter the conent in  some way before sending back to client.
                var newContent = new StringContent("It's all greek...er, Latin...to me!");
                hrm.Content = newContent;
            })
            .WithHandleFailure((c, e) =>
            {
                // Return a custom error response.
                c.Response.StatusCode = 403;
                c.Response.WriteAsync("Things borked.");
            });

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

Also, adds X-Forwarded-* and Forwarded headers.

twitchax commented 5 years ago

@digitalpowers, @wasabii, @urffin, take a look?

wasabii commented 5 years ago

Neat. I believe the host header should probably have the port in it.

And I think you need to do special formatting for ipv6.

urffin commented 5 years ago

Seems not bad, do you think about Func<> instead Action in callback, so instead

.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;
    })

use

.WithAfterReceive((c, hrm) =>
    {
        // Alter the content in  some way before sending back to client.
        return  new StringContent("It's all greek...er, Latin...to me!");
    })
twitchax commented 5 years ago

@urffin, no, since the current Action lets the user override any part of the HttpResponseMessage. I have gone back and forth between an Action that allows you to edit the response, versus a Func that requires you to return a new one.

I stuck with the Action because I think the 80% case is to make small adjustments to the response in the form of headers, etc.

twitchax commented 5 years ago

@wasabii, it looks like the Host header can have an optional port. I will add that.

I will also fix the IPv6 case.

twitchax commented 5 years ago

@digitalpowers, @wasabii, @urffin, any other comments?

urffin commented 5 years ago

@twitchax, i can look deeper only in saturday

twitchax commented 5 years ago

@urffin, addressed your comments.

urffin commented 5 years ago

@twitchax, don't forget merge to master :-)