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

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

问题描述

使用asp.net core web 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;字符集=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
andom_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 IActionResult Get()
{
    var image = System.IO.File.OpenRead("C:\test\random_image.jpeg");
    return File(image, "image/jpeg");
}

说明:

在 ASP.NET Core 中,您必须使用控制器内部的内置 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天全站免登陆