我有一个可通过使用ASP.NET Web API 2.1配置的REST API访问的函数,该函数应将图像返回给调用者。出于测试目的,我只返回了当前存储在本地计算机上的示例图像。方法如下:
public IHttpActionResult GetImage()
{
FileStream fileStream = new FileStream("C:/img/hello.jpg", FileMode.Open);
HttpContent content = new StreamContent(fileStream);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
content.Headers.ContentLength = fileStream.Length;
return Ok(content);
}
调用此方法后,我什么都没有得到。这是我收到的回复:
为什么我没有在请求中取回图像数据?如何解决?
最佳答案
一种可能是编写自定义IHttpActionResult
来处理图像:
public class FileResult : IHttpActionResult
{
private readonly string filePath;
private readonly string contentType;
public FileResult(string filePath, string contentType = null)
{
this.filePath = filePath;
this.contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(filePath))
};
var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return response;
}, cancellationToken);
}
}
您可以在Web API Controller 操作中使用的代码:
public IHttpActionResult GetImage()
{
return new FileResult(@"C:\\img\\hello.jpg", "image/jpeg");
}