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

查看:28
本文介绍了如何使用 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 core 的问题.在 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 core (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天全站免登陆