如何使用Web API Get方法返回图像 [英] How to to return an image with Web API Get method

查看:267
本文介绍了如何使用Web API Get方法返回图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Web API Get方法返回图像.下面的代码似乎正常工作,除了我在Fiddler的ImageView窗口中收到此消息外,此响应已编码,但并不声称是图像."

I need to return an image with a Web API Get method. The code below seems to work fine except that I get this message in the Fiddler's ImageView window, "This response is encoded, but does not claim to be an image."

public HttpResponseMessage Get()
{
    using (FileStream fs = new FileStream(filePath, FileMode.Open))
    {
        HttpResponseMessage response = new HttpResponseMessage(); 
        response.Content = new StreamContent(fs);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        return response;
    }
} 

我在Fiddler中也看到了与此代码相同的结果:

I see the same result in the Fiddler with this code also:

public HttpResponseMessage Get()
{
    HttpResponseMessage response = new HttpResponseMessage();
    Byte[] b = (GetImageByteArray());
    response.Content = new ByteArrayContent(b);
    response.Content.LoadIntoBufferAsync(b.Length).Wait();
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    return response;
}

如果我使用.png格式,则会得到相同的结果.

I get the same result if I use .png format.

感谢您的帮助,

推荐答案

如果我理解正确,那么您将要求特定于asp.net核心.在ASP.net核心HttpResponseMessage中,我们无法像在ASP.net Web API 2中那样返回结果.

If I understand correctly then you are asking specific to asp.net core. In ASP.net core HttpResponseMessage is not a way to return result the way we used to do in ASP.net web api 2.

在asp.net核心(WEB API)中,看起来就像这样.

In asp.net core ( WEB API ) simply look like this.

[HttpGet]
public IActionResult Get()
{            
    Byte[] b = System.IO.File.ReadAllBytes(@"E:\\Test.jpg");   // You can use your own method over here.         
    return File(b, "image/jpeg");
}

注意:正如您提到的那样,在Fiddler Imageview中,您会看到类似这样的消息:他的响应已编码,但并不声称是图像."因为ASP.net核心将HttpResponseMessage视为简单类并转换为json或xml.

Note: As you mention that in Fiddler Imageview you see message like this "his response is encoded, but does not claim to be an image." because ASP.net core consider HttpResponseMessage as simple class and convert into json or xml.

这篇关于如何使用Web API Get方法返回图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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