AspNetCore.Proxy icon indicating copy to clipboard operation
AspNetCore.Proxy copied to clipboard

Post Requests?

Open DavidBrower opened this issue 4 years ago • 2 comments

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?

DavidBrower avatar Aug 30 '21 15:08 DavidBrower

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

twitchax avatar Sep 07 '21 05:09 twitchax

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.

joaocpribeiro avatar Oct 06 '21 09:10 joaocpribeiro