如何使用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。
- DNX SDK版本’dnx-clr-win-x86.1.0.0-beta8-15530’无法安装
- 如何使用UserManager在IdentityUser上加载导航属性
- 从类库访问Asp.net-core中的appsetting.json
- 使用XUnit和ASP.NET Core 1.0进行dependency injection
- 如何在asp.net核心中获取项目的根目录。 Directory.GetCurrentDirectory()似乎无法在mac上正常工作
- ASP.NET Core 2.0禁用自动挑战
- 如何在ASP.NET Core中解析ConfigureServices中的实例
- 如何在ASP.NET Core中设置强类型配置?
- 从ASP.NET Core 1.1 MVC迁移到2.0后,自定义cookie身份validation无法正常工作