为什么我的文件不被从Web API函数GET请求返回? [英] Why is my file not being returned by a GET request from my Web API function?

查看:223
本文介绍了为什么我的文件不被从Web API函数GET请求返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过我的REST API,用的ASP.NET Web API 2.1配置访问的功能,这应该图像返回给调用者。出于测试目的,我只是把它回来时,我现在都存储在我的本地计算机上的样本图像。这里是方法:

I have a function accessible through my REST API, configured with ASP.NET Web API 2.1, that should return an image to the caller. For testing purposes, I just have it returning a sample image I have stored on my local machine right now. Here is the method:

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);
         }

当这个方法被调用,我没有得到的图像回来的。下面是我收到的回应:

When this method gets called, I am not getting an image back at all. Here is the response I am receiving:

{\"Headers\":[{\"Key\":\"Content-Type\",\"Value\":[\"image/jpeg\"]},{\"Key\":\"Content-Length\",\"Value\":[\"30399\"]}]}

{"Headers":[{"Key":"Content-Type","Value":["image/jpeg"]},{"Key":"Content-Length","Value":["30399"]}]}

为什么我没有得到的图像数据早在请求的一部分?这怎么解决?

Why am I not getting the image data back as part of the request? How can that be resolved?

推荐答案

一种可能性是写一个自定义的 IHttpActionResult 来处理图像:

One possibility is to write a custom IHttpActionResult to handle your images:

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控制器动作是:

that you could use in your Web API controller action:

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

这篇关于为什么我的文件不被从Web API函数GET请求返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆