我想从网址下载图片并通过控制器提供。理想情况下,我希望尽可能地流式传输,而不是尝试创建字节数组等。
我通过我的控制器下载文件的原因,而不仅仅是向消费者提供foo.ImageUrl
是因为网址是http而我代理以避免混合内容。通过将绝对URL放入html img
标记
这是我到目前为止所做的:
问题是图像似乎没有任何内容。 img
标记看起来是空白的,当我在浏览器中导航到它时,我只看到标题而没有尝试下载?
如何从网址下载并将其作为流方式返回给来电者工作?
[HttpGet]
[AllowAnonymous]
[Route(template: "Reward/FooLogo/{fooId}/bar/{barId}", Name = "FooLogo")]
public async Task<StreamContent> FooLogo(int fooId, int barId)
{
var foo = await GetFooAsync(fooId, barId);
if (string.IsNullOrWhiteSpace(foo?.ImageUrl))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
using (var response = await WebRequest.Create(foo.ImageUrl).GetResponseAsync())
{
// todo check content type
var responseStream = response.GetResponseStream();
var content = new StreamContent(responseStream);
content.Headers.ContentType = new MediaTypeHeaderValue(response.ContentType);
content.Headers.ContentLength = response.ContentLength;
return content;
}
}
答案 0 :(得分:4)
仅删除using
似乎没有解决我的问题。我已经重写了一下,这似乎解决了我的问题。
[HttpGet]
[AllowAnonymous]
[Route(template: "Reward/FooLogo/{fooId}/bar/{barId}", Name = "FooLogo")]
public async Task<HttpResponseMessage> FooLogo(int fooId, int barId)
{
var foo = await GetFooAsync(fooId, barId);
if (string.IsNullOrWhiteSpace(foo?.ImageUrl))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
using (var client = new HttpClient())
{
var res = await client.GetAsync(paymentMethod.ImageUrl);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(await res.Content.ReadAsStreamAsync());
response.Content.Headers.ContentType = res.Content.Headers.ContentType;
return response;
}
}