簡體   English   中英

Web API odata操作方法以返回圖像

[英]web api odata action method to return image

我們正在使用asp.net Web API odata實體集控制器獲取用戶配置文件。 代表單個用戶個人資料的網址如下所示

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." 

我認為問題在於關閉 FileStream。

不要關閉流,因為Web API的托管層會關閉它。 另外,您無需顯式設置content-length.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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM