小编J.D*_*.D.的帖子

如何使用Web API Get方法返回图像

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

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;
    }
} 
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

感谢您的帮助,

c# asp.net-web-api asp.net-core

26
推荐指数
3
解决办法
4万
查看次数

标签 统计

asp.net-core ×1

asp.net-web-api ×1

c# ×1