如何使用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; } } 

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

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

感谢您的帮助,

如果我理解正确,那么你要求具体到asp.net核心。 在ASP.net核心中,HttpResponseMessage不是像我们以前在ASP.net web api 2中那样返回结果的方法。

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

 [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。