从Asp.Net Core WebAPI返回jpeg图像 [英] Return jpeg image from Asp.Net Core WebAPI

查看:1726
本文介绍了从Asp.Net Core WebAPI返回jpeg图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 asp.net核心网络api ,我想使用控制器操作方法来返回 jpeg图像流.
在我当前的实现中,浏览器仅显示json字符串. 我的期望是在浏览器中看到图像.

Using asp.net core web api, I want to have my controller action method to return an jpeg image stream.
In my current implementation, browser displays only a json string. My expectation is to see the image in the browser.

在使用chrome开发人员工具进行调试时,我发现内容类型仍然是

While debugging using chrome developer tools I found that the content type is still

Content-Type:application/json; charset=utf-8

即使在我的代码中我手动将内容类型设置为"image/jpeg",也返回了响应头.

returned in the response header, even though in my code I manually set the content type to "image/jpeg".

寻找解决方案我的Web API如下

Looking for a solution My Web API is as below

[HttpGet]
public async Task<HttpResponseMessage> Get()
{
    var image = System.IO.File.OpenRead("C:\\test\random_image.jpeg");
    var stream = new MemoryStream();

    image.CopyTo(stream);
    stream.Position = 0;            
    result.Content = new StreamContent(image);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "random_image.jpeg";
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    result.Content.Headers.ContentLength = stream.Length;

    return result;
}

推荐答案

清洁溶液使用FilestreamResult !!

[HttpGet]
public async Task<IActionResult> Get()
{
    var image = System.IO.File.OpenRead("C:\\test\\random_image.jpeg");
    return File(image, "image/jpeg");
}

说明:

在ASP.NET Core中,您必须使用Controller内部的内置 File()方法.这将允许您手动设置内容类型.

In ASP.NET Core you have to use the built-in File() method inside the Controller. This will allow you to manually set the content type.

不要创建和返回HttpResponseMessage,就像您曾经在ASP.NET Web API 2中使用过一样.它什么也不做,甚至不会引发错误!

Don't create and return HttpResponseMessage, like you were used to using in ASP.NET Web API 2. It doesn't do anything, not even throwing errors!!

这篇关于从Asp.Net Core WebAPI返回jpeg图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆