如何将HTTP响应转发到客户端 [英] How to forward HTTP response to client
问题描述
我有一个客户端(Xamarin)和两个Web API服务器A和B.客户端向A发出请求,A使用请求参数向B发出另一个请求.如何返回A从B收到的响应对客户来说,使得B对C的使用对客户是透明的.
I have a client (Xamarin) and two Web API servers, A and B. The client makes a request to A which uses the request parameters to make another request to B. How do I return the response that A receives from B to the client such that B's use of C is transparent to the client.
例如,如果我使用HttpClient
从A到B发出请求,如何通过控制器的操作将HttpResponseMessage
转发给客户端?
For example, if I make a request from A to B using HttpClient
how do I forward the HttpResponseMessage
to the client in a controller's action?
推荐答案
查看 aspnet/AspLabs 透明HTTP代理的一个很好的例子的存储库. 该代理是一个中间件,用于处理客户端对A的请求并向B进行自身的请求.
Look at aspnet/AspLabs repository for a good example of a transparent HTTP proxy. This proxy is a middleware handling client's requests to A and making its own requests to B.
要提供完整的答案,这是其源代码的一部分,实际上是转发HttpResponseMessage
:
To provide a complete answer, this is the part of its source code which is actually forwarding a HttpResponseMessage
:
using (var responseMessage = await _httpClient.SendAsync(
requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
context.Response.StatusCode = (int)responseMessage.StatusCode;
foreach (var header in responseMessage.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
foreach (var header in responseMessage.Content.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
// SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
context.Response.Headers.Remove("transfer-encoding");
await responseMessage.Content.CopyToAsync(context.Response.Body);
}
有完整代码将收到的HttpResponseMessage
复制到存储库中的HttpContext.Response
.
There is full code copying a received HttpResponseMessage
to the HttpContext.Response
in the repository.
这篇关于如何将HTTP响应转发到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!