han*_*ans 38 content-type asp.net-core asp.net-core-webapi
使用asp.net核心web api,我想让我的控制器动作方法返回一个jpeg图像流.
在我当前的实现中,浏览器仅显示json字符串.我的期望是在浏览器中看到图像.
在使用chrome开发人员工具进行调试时,我发现内容类型仍然存在
Content-Type:application/json; charset=utf-8
在响应头中返回,即使在我的代码中我手动将内容类型设置为"image/jpeg".
寻找解决方案 My Web API如下所示
[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;
}
Run Code Online (Sandbox Code Playgroud)
han*_*ans 61
清洁溶液使用FilestreamResult!!
[HttpGet]
public async Task<IActionResult> Get()
{
var image = System.IO.File.OpenRead("C:\\test\\random_image.jpeg");
return File(image, "image/jpeg");
}
Run Code Online (Sandbox Code Playgroud)
说明:
在ASP.NET Core中,您必须使用Controller内部的内置 File()方法.这将允许您手动设置内容类型.
不要HttpResponseMessage像以前在ASP.NET Web API 2中使用那样创建和返回.它不会做任何事情,甚至不会抛出错误!
PhysicalFile使用简单的语法帮助从Asp.Net Core WebAPI返回文件
[HttpGet]
public IActionResult Get(int imageId)
{
return new PhysicalFile(@"C:\test.jpg", "image/jpeg");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28269 次 |
| 最近记录: |