在一个 ASP.NET Core Controller Action 中,通过 HttpClient 请求后端的一个 web api ,想把 web api 的响应(HttpResponseMessage)直接发送给客户端,代码如下:
public async Task<IActionResult> MarkdownToHtmlPorxy()
{
var response = await _markdownNodeApi.PostAsync(
Request.GetEncodedPathAndQuery(),
new StreamContent(Request.Body));
// How to send HttpResponseMessage to client
}
请问如何实现?
通过下面的代码实现了。
public async Task<IActionResult> MarkdownToHtmlPorxy()
{
var apiResponse = await _markdownNodeApi.PostAsync(
Request.GetEncodedPathAndQuery(),
new StreamContent(Request.Body));
Response.OnStarting(() =>
{
foreach (var header in apiResponse.Headers)
{
if (Response.Headers.ContainsKey(header.Key))
{
Response.Headers[header.Key] = header.Value.FirstOrDefault();
}
else
{
Response.Headers.Add(header.Key, header.Value.FirstOrDefault());
}
}
return Task.CompletedTask;
});
await apiResponse.Content.CopyToAsync(Response.Body);
return new EmptyResult();
}
dudu哈哈哈哈
stackoverflow 相关链接:Correct way to return HttpResponseMessage as IActionResult in .Net Core 2.2
– dudu 4年前