【问题标题】:web api odata action method to return image返回图像的 web api odata 操作方法
【发布时间】:2013-06-11 20:36:00
【问题描述】:

我们正在使用 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." 

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • @Kiran-Challa 上传文件怎么样?我找不到任何使用 wep api odata 执行此操作的好例子
    • 我和@CoffeeCode 有同样的问题。你在做什么上传?在网上找不到很好的例子。谢谢。
    猜你喜欢
    • 2014-11-22
    • 1970-01-01
    • 2017-01-03
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2012-08-04
    相关资源
    最近更新 更多