我有一个客户端(Xamarin)和两个Web API服务器A和B.客户端向A发出请求,该请求使用请求参数向B发出另一个请求。如何返回A从B接收的响应对客户来说,B对C的使用对客户来说是透明的。
例如,如果我使用HttpClient
从A到B发出请求,如何在控制器的操作中将HttpResponseMessage
转发给客户?
答案 0 :(得分:6)
查看Microsoft ASP.NET Core Proxy存储库以获取透明HTTP代理的一个很好的示例。 此代理是一个中间件,处理客户端对A的请求并向B发出自己的请求。
为了提供完整的答案,这是其源代码的一部分,实际上是转发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);
}
从2019年开始更新:在原始答案发布后,代理完全被重新设计。这是updated code将收到的HttpResponseMessage
复制到HttpContext.Response
。此外,整个项目稍后存档。检查存储库自述文件以获取有关正在进行的开发的更多信息。
答案 1 :(得分:0)
这是服务器端:
WebForm1.aspx.cs中
protected void Page_Load(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(10);
client.GetAsync("http://localhost:14388/WebForm2.aspx").ContinueWith(
getTask =>
{
if (getTask.IsCanceled)
{
Console.WriteLine("Request was canceled");
}
else if (getTask.IsFaulted)
{
Console.WriteLine("Request failed: {0}", getTask.Exception);
}
else
{
HttpResponseMessage response = getTask.Result;
string _message = response.Content.ReadAsStringAsync()
.Result
.Replace("\\", "")
.Trim(new char[1] { '"' });
}
});
}
WebForm2.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Volkan.WebForm2" %>
WebForm2.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("ahada cevabım");
}
答案 2 :(得分:0)
我接受了IIya的回答,并将其改编为asp.net MVC 5
public async Task GetFile(CancellationToken cancellationToken)
{
var context = HttpContext;
var _httpClient = StaticHttpClient.Instance;
var requestMessage = new HttpRequestMessage()
{
RequestUri = new Uri("https://localhost:44305/api/files/123"),
};
using (var responseMessage = await _httpClient.SendAsync(
requestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
Response.StatusCode = (int)responseMessage.StatusCode;
foreach (var header in responseMessage.Headers)
{
Response.Headers[header.Key] = header.Value.First();
}
foreach (var header in responseMessage.Content.Headers)
{
Response.Headers[header.Key] = header.Value.First();
}
Response.Headers.Remove("transfer-encoding");
//Response.BinaryWrite(await responseMessage.Content.ReadAsByteArrayAsync());
await responseMessage.Content.CopyToAsync(Response.OutputStream);
Response.Flush();
Response.Close();
context.ApplicationInstance.CompleteRequest();
}
}