2

我们正在使用 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)/picture

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

1 回答 1

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;
}
于 2013-06-11T20:46:19.133 回答