【问题标题】:HttpGet to return image and IdHttpGet 返回图片和ID
【发布时间】:2018-01-14 06:27:27
【问题描述】:

我下面有一个用于返回图像和 id 的函数。在测试时,我看不到我的 id 被返回,相反,我只能看到在我的浏览器中返回的图像(可能是因为它完全是字节数据)。

            int id = 0;
            using (Bitmap bitmap = Image.Generate(context, out id))
            {
                HttpResponse response = context.Response;
                response.CacheControl = "no-cache";
                response.ContentType = "image/JPG";
                bitmap.Save(response.OutputStream, ImageFormat.Jpeg);
                response.End();

                var responseModel = new ResponseModel
                {
                    Id = id,
                    Image = bitmap
                };

                return Ok(responseModel);
            };

chrome 中的响应预览:

如果包含图像,这是返回响应的适当方式吗?如果是这样,我如何从 ajax 调用中获取此响应数据,包括图像和 ID(可以使用 Json.parse 完成吗?但这是字节数据)?

【问题讨论】:

    标签: ajax http asp.net-web-api


    【解决方案1】:

    您可以做的一件事是在 HttpResponseMessage 的标题中添加 Id,就像这个答案一样

    Asp.net Web API return File with metadata about the file

    我在移动设备上,所以我稍后会更新我的答案,但基本上你只需要将图像作为消息的正文和标题中的任何元数据。然后在客户端只需解析响应标头即可获得所需的内容。我以前用过这个。

    承诺的样品

    public HttpResponseMessage Get()
    {
        XDocument xDoc = GetXMLDocument();
        int id = CallToGetMyId();
    
        var response = this.Request.CreateResponse(
            HttpStatusCode.OK, 
            xDoc.ToString(), 
            this.Configuration.Formatters.XmlFormatter
        );
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "image.png"
        };
        response.Headers.Add("Id", id);
        return response;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-05
      • 2018-06-16
      • 2021-12-07
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多