问题描述
我有一个4.7.2应用程序,我正在尝试在.net core 3.1中重写它。
我在下面的控制器中有一个方法。当然,实际代码是不同的,我收到一些参数并生成URL等。但是想法是相同的。我试图反映另一台服务器的响应。
[Route("images")]
public async Task<HttpResponseMessage> Getimage()
{
Uri uri = new Uri("https://img-lcwaikiki.mncdn.com/mnresize/1024/-/pim/productimages/20202/4353414/l_20202-0w9011z8-hrz_a.jpg",UriKind.Absolute);
using (HttpClient client = new HttpClient())
{
return await client.GetAsync(uri);
}
}
但是有趣的是,.net框架和核心的作用完全不同。
框架,按预期返回图像(.net Framework 4.7.2 Sample)。
但是core会在正文(.net Core 3.1 Sample)中返回一个json。
我已经检查了Microsoft文档,netCore 3.1和.net Framework 4.7.2中的Sytem.Net.Http.HttpClient类都是相同的。
要进行复制,您可以创建一个新的netCore和.netFramework应用程序。顺便说一句,我已经为此项目创建了一个仓库: https://github.com/fkucuk/imagereflectorhttpclient
解决方法
.NET Framework和.NET Core框架之间,从client.GetAsync
返回的HttpResponseMessage的处理方式似乎有所不同。
.NET Framework要么直接返回HttpResponseMessage到API客户端,要么检索内容并将其包装到另一个HttpResponseMessage中,然后再将其返回给客户端,.NET Core会将其视为对象,并使用默认媒体转换器(JSON此处)进行转换,然后将其再次包装到另一个HttpResponseMessage中,并返回到您的API的客户端。
此外,随着.NET Core的最新开发,HttpResponseMessage也不太可能用于Web API。您可以使用IActionResult
来从API返回几乎任何形式的响应。
您可以详细了解here
为解决您的问题,以下是我的建议。
[HttpGet]
public async Task<IActionResult> Get()
{
Uri uri = new Uri("https://img-lcwaikiki.mncdn.com/mnresize/1024/-/pim/productimages/20202/4353414/l_20202-0w9011z8-hrz_a.jpg",UriKind.Absolute);
using (HttpClient client = new HttpClient())
{
using (var stream = await client.GetStreamAsync(uri))
{
return File(stream,"image/jpeg");
}
}
}
,
感谢Chetan, 我猜您提供的解决方案不会返回文件本身。
我想出了以下解决方案。
但是我不确定这是否会导致泄漏。我不处理流。
[HttpGet]
[Route("v1")]
public async Task<IActionResult> GetImage1()
{
Uri uri = new Uri("https://img-lcwaikiki.mncdn.com/mnresize/1024/-/pim/productimages/20202/4353414/l_20202-0w9011z8-hrz_a.jpg",UriKind.Absolute);
using (HttpClient client = new HttpClient())
{
var response = await client.GetAsync(uri);
var stream = await response.Content.ReadAsStreamAsync();
return File(stream,"image/jpeg");
}
}