为什么我的文件没有被我的Web API函数的GET请求返回?

Jim*_*Jim 16 .net c# rest asp.net-web-api

我有一个函数可以通过我的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);
         }
Run Code Online (Sandbox Code Playgroud)

当调用此方法时,我根本没有得到图像.以下是我收到的回复:

{ "接头":[{ "密钥": "内容类型", "值":[ "图像/ JPEG"]},{ "密钥": "内容长度", "值":[ "30399"] }]}

为什么我没有将图像数据作为请求的一部分返回?怎么解决这个问题?

Dar*_*rov 30

一种可能性是编写自定义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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在Web API控制器操作中使用:

public IHttpActionResult GetImage()
{
    return new FileResult(@"C:\\img\\hello.jpg", "image/jpeg");
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么他们不能只提供这个开箱即用?! (9认同)
  • 是`Task.Run`是必要的吗?`Task.FromResult`不会足够吗? (2认同)