2

I am writing a middle tier service which, for context, forwards requests to a "secret" url owned by an external team, and performs auth/authZ on the request.

I'm looking for a way to return the HttpResponseMessage directly to the caller, such that the two response objects (the one I've received, and the one callers of my API receive) would look the same (or as close to it as possible)

my API is defined like so

    [Route("proxy/{input1}")]
    [Authorize(Policy = "Admin")]
    public async Task/*<SomeType>*/ ProxyCall(string input1)
    {
        var client = new HttpClient();
        var request = httpContextAccessor.HttpContext?.Request;
        var uriToCall = QueryHelpers.AddQueryString(LookupUri(input1), request.Query.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString()));
        var httpContent = new StreamContent(request.Body);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue(request.ContentType);
            httpContent.Headers.ContentLength = request.ContentLength;
        var executionRequest = new HttpRequestMessage(new HttpMethod(GetMethodForHost(uriToCall)), uriToCall) { Content = httpContent };

        var response = await client.SendAsync(executionRequest);
        /* I now have an HttpResponseMessage object. I want this response object
        to be returned as is*/

        /* 
        // This returns a json object which is the HttpRequestMessage serialized to json, with 200 status code

        return response;
        */

        /* 
        // This looks close, but the body is always empty
        var responseStream = await result.Content.ReadAsStreamAsync();
        Response.Body = responseStream;
        Response.StatusCode = (int)result.StatusCode;
        foreach(var header in result.Headers)
        {
            Response.Headers.Add(header.Key, new StringValues(header.Value.ToArray()));
        }
        */
    }

I've tried toying around with returning ObjectContent etc. however what I'd like most is to see a simple, elegant way to return the message response as is, status code, headers, content etc. included

ElFik
  • 715
  • 7
  • 25
  • This looks like a use case for building a custom `IActionResult` that would populate the response as you described when executed. – Nkosi May 31 '18 at 02:30
  • 2
    I have since found [this thread](https://stackoverflow.com/questions/42000362/creating-a-proxy-to-another-web-api-with-asp-net-core?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) which my question is a duplicate of – ElFik May 31 '18 at 02:37
  • Yep saw that repository as well. Give it a try and see if that works out – Nkosi May 31 '18 at 02:40
  • Indeed it works! I think it was a case of PEBKAC when I was trying to use the `Response.Body` approach, this looks to be working – ElFik May 31 '18 at 02:44
  • I guess it was one of those "There's an extension for that" cases. – Nkosi May 31 '18 at 02:45

0 Answers0