web api odata动作方法返回图像

时间:2013-06-11 20:36:01

标签: c# asp.net-web-api odata

我们正在使用asp.net web api odata entitysetcontroller来获取用户个人资料。表示单个用户配置文件的网址如下所示

http://www.domain.com/api/org/staff(123)

现在商务要求我们提供用户图像作为用户配置文件的一部分。所以我在exisitng控制器中添加了一个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;
        }
    }

我尝试了以下网址进行测试并成功执行了该方法。但问题是我总是收到状态为504的错误消息作为最终响应。

http://www.domain.com/api/org/staff(123)/picture

"ReadResponse() failed: The server did not return a response for this request." 

1 个答案:

答案 0 :(得分:4)

我认为问题出在关闭 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;
}
相关问题