Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

c# - How to to return an image with Web API Get method

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

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

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

Appreciate your help,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...