我有一个为 DMZ(互联网)服务器提供服务的 Intranet WebAPI 服务器。
API 操作:
[HttpGet]
public HttpResponseMessage ImagePath(string filePath)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return result;
}
该 api 确实成功返回了图像。 我想继续从 DMZ 到 Intranet 的请求,但我不知道如何编写操作,我的代码如下:
public async Task<HttpResponseMessage> ImagePath(string filePath)
{
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
};
using (var client = new HttpClient(handler)) {
client.BaseAddress = new Uri(apiUrl); //apiUrl is my intranet domain
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("image/jpeg"));
HttpResponseMessage fs = await client.GetAsync("cipap/api/baseapi/ImagePath?filePath=" + filePath);
return fs;
}
//FileStream fs = new FileStream(filePath, FileMode.Open);
//return File(fs, "image/jpeg");
}
有人能帮帮我吗?非常感谢。
最佳答案
终于找到答案了,
只需执行 FileResult 类型的操作,
并通过以下方式返回文件:
File(fs.Content.ReadAsByteArrayAsync().Result, "image/jpeg");
还有一件事是在 webapi 操作中,我需要如下配置文件流,否则文件将在第一次请求后被锁定:
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
public async Task<FileResult> ImagePath(string filePath)
{
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
};
using (var client = new HttpClient(handler)) {
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("image/jpeg"));
HttpResponseMessage fs = await client.GetAsync("cipap/api/baseapi/ImagePath?filePath=" + filePath);
return File(fs.Content.ReadAsByteArrayAsync().Result, "image/jpeg");
}
}
引用: Download file prompt when using WebAPI HttpResponseMessage
关于c# - 来自 WebAPI 的服务器调用图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292444/