返回图像的Web API数据操作方法
本文关键字:数据 操作方法 API Web 图像 返回 | 更新日期: 2023-09-27 18:18:08
我们使用asp.net web api odata entitysetcontroller来获取用户配置文件。表示单个用户配置文件的url如下所示
http://www.domain.com/api/org/staff (123)
现在业务要求我们提供用户图像作为用户配置文件的一部分。所以我给现有的控制器添加了一个odata动作方法。
var staff = builder.EntitySet<Contact>("staff"); //regiester controller
var staffAction = staff.EntityType.Action("picture"); //register action method
staffAction.Returns<System.Net.Http.HttpResponseMessage>();
控制器中的odata动作方法如下
[HttpPost]
public HttpResponseMessage Picture([FromODataUri] int key)
{
var folderName = "App_Data/Koala.jpg";
string path = System.Web.HttpContext.Current.Server.MapPath("~/" + folderName);
using (FileStream mem = new FileStream(path,FileMode.Open))
{
StreamContent sc = new StreamContent(mem);
HttpResponseMessage response = new HttpResponseMessage();
response.Content = sc;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
response.Content.Headers.ContentLength = mem.Length;
response.StatusCode = HttpStatusCode.OK;
return response;
}
}
我尝试了以下url进行测试,并且成功执行了该方法。然而,问题是我总是收到状态为504的错误消息作为最终响应。
http://www.domain.com/api/org/staff(123)/图片"ReadResponse() failed: The server did not return a response for this request."
我认为问题在于关闭 FileStream。
不要关闭流,因为Web API的托管层会关闭它。同时,你需要不显式设置内容长度。StreamContent为您设置。
[HttpPost]
public HttpResponseMessage Picture([FromODataUri] int key)
{
var folderName = "App_Data/Koala.jpg";
string path = System.Web.HttpContext.Current.Server.MapPath("~/" + folderName);
StreamContent sc = new StreamContent(new FileStream(path,FileMode.OpenRead));
HttpResponseMessage response = new HttpResponseMessage();
response.Content = sc;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
response.StatusCode = HttpStatusCode.OK;
return response;
}