twitchax / AspNetCore.Proxy

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

Post Requests? #82

Open DavidBrower opened 3 years ago

DavidBrower commented 3 years ago

I've been puzzling how to use AspNetCore.Proxy to forward a Post request to a Web API Controller. Currently, the code looks like this:

   [HttpPost]
    [Route("[action]")]
    public async Task<ActionResult> Login(LoginViewModel model)
    {
        //return ProxyTo(serverUrl, LoginUri, model);
        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = await httpClient.PostAsync(serverUrl + LoginUri, new JsonContent(model));
        return Ok(response);
    }

How would I rewrite this to use AspNetCore.Proxy?

twitchax commented 3 years ago

Hi @DavidBrower, sorry for the delay: I fractured my clavicle, and was out for a bit.

You don't need to return a response: the proxy function does everything for you. Check out this sample.

[Route("api/google/{**rest}")]
public Task ProxyCatchAll(string rest)
{
    // If you don't need the query string, then you can remove this.
    var queryString = this.Request.QueryString.Value;
    return this.HttpProxyAsync($"https://google.com/{rest}{queryString}");
}
joaocpribeiro commented 2 years ago

For swagger purposes, I wanted to maintain the content model in the endpoint definition. Therefore I could manage to forward the content with the following code:

var httpProxyOptions = HttpProxyOptionsBuilder.Instance
                .WithBeforeSend((c, hrm) =>
                {
                    hrm.Content = new StringContent(JsonConvert.SerializeObject(requestModel), Encoding.UTF8, "application/json");
                    return Task.CompletedTask;
                })
                .Build();

I hope this helps someone.