我有一个可通过我的 REST API 访问的函数,它配置了 ASP.NET Web API 2.1,它应该向调用者返回一个图像。出于测试目的,我只是让它返回我现在存储在本地机器上的示例图像。方法如下:
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);
}
调用此方法时,我根本没有取回图像。这是我收到的回复:
{"Headers":[{"Key":"Content-Type","Value":["image/jpeg"]},{"Key":"Content-Length","Value":["30399"]}]}
为什么我没有在请求中取回图像数据?如何解决?
最佳答案
一种可能性是编写自定义 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");
}
关于c# - 为什么我的文件没有被我的 Web API 函数的 GET 请求返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23768596/