服务图像 - 关闭图像资源

时间:2015-02-03 23:41:53

标签: c# asp.net-mvc-4 asp.net-web-api

以下代码完美无缺。它服务于指定的图像。

  public HttpResponseMessage Get(string id)     
  {
      string fileName = string.Format("{0}.png", id);
      FileStream fileStream = File.Open(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + fileName), FileMode.Open);
      HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
      response.Content.Headers.ContentLength = fileStream.Length;
      return response;
  }

只是为了释放我获取的资源来读取图像文件,我修改了代码如下。

public HttpResponseMessage Get(string id)     
{
   string fileName = string.Format("{0}.png", id);
   using (FileStream fileStream = File.Open(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + fileName), FileMode.Open))
       {
            HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
            response.Content.Headers.ContentLength = fileStream.Length;
            return response;
        }
}

我收到错误“将内容复制到流时出错”。是。我在流式传输之前关闭了资源。

但问题是如何提供图像并仍然关闭未处理的资源? Asp.Net Web API 2及更高版本。 谢谢你的想法。

1 个答案:

答案 0 :(得分:1)

您无需担心发布FileStream对象。一旦响应完成,它将由较低层的Web API关闭。您的第一个代码段中提到的代码很好。