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

时间:2016-08-27 04:49:48

标签: c# asp.net-web-api asp.net-core

我需要使用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格式,我会得到相同的结果。

感谢您的帮助,

4 个答案:

答案 0 :(得分:32)

如果我理解正确,那么你要求具体到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。

答案 1 :(得分:1)

这是我从项目中的API获取图像的方式。我分享关注的人。

图像内容保存到服务器上的“图像”文件夹中,图像名称保存到数据库中。

[Route("api/dashboard/GetImage")]
public byte[] GetImage(int componentId)
{
            using (var dashboardService = new DashboardService())
            {
                var component = dashboardService.GetImage(componentId);
                var context = HttpContext.Current;
                string filePath = context.Server.MapPath("~/Images/" + component.ImageName);
                context.Response.ContentType = "image/jpeg";
                using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        fileStream.CopyTo(memoryStream);
                        Bitmap image = new Bitmap(1, 1);
                        image.Save(memoryStream, ImageFormat.Jpeg);

                        byte[] byteImage = memoryStream.ToArray();
                        return byteImage;
                    }
                }
            }
}

获取Angular中的图像内容

this.dashboardService.getImage(this.componentId)
    .subscribe((blob: any) => {
      let objectURL = 'data:image/jpeg;base64,' + blob;
      this.imageUrl = this.sanitizer.bypassSecurityTrustUrl(objectURL);;
});

答案 2 :(得分:0)

添加此答案是因为这些评论很容易被遗漏(就像我几乎一样)。

由Jussi Palo建议(使用PhysicalFileResult):

[HttpGet]
public IActionResult Get()
{        
    return PhysicalFile(@"E:\\Test.jpg", "image/jpeg");
}
  • 一个很好的单一衬板,可以处理206局部之类的东西。

由Tseng建议(使用接受流的FileContentResult构造函数的重载):

[HttpGet]
public IActionResult Get()
{        
    FileStream stream = File.Open(@"E:\\Test.jpg");
    return File(stream, "image/jpeg");
}
  • 如果流来自其他地方(例如嵌入式资源),则很有用。

对于RL,请记住检查文件/资源​​是否存在,如果不存在,则返回404。

答案 3 :(得分:0)

除了先前的答案外,还可以使用它来基于System.Web.Hosting命名空间中的托管环境获取图像。

var imageUrl = HostingEnvironment.MapPath("~/images/photo.png");

并使用imageUrl来查找图像的byte[],并使用适当的内容类型(例如image/jpeg

进行处理)