处理来自web api的图像时,图像为空白

时间:2016-10-26 19:40:36

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

我有2个web api。连接到数据库并获取数据的人(webapi 2)。另一个只处理这些数据并发送到客户端(webapi 1)。 问题是,当是一个字符串时,句柄是Works。但随着图像不起作用。我收到一般内部服务器错误500。 如果我只调用WebApi 2,我会得到图像。如果我调用调用webapi 2的WebApi 1,则图像为空白。

我的网络Api处理程序:

[HttpGet]
[Route("Foto")]
public async Task<HttpResponseMessage> GetFoto(string suspid, string pk)
{
    HttpClientHandler handler = new HttpClientHandler()
    {
        UseDefaultCredentials = true,
    };

    using (var client = new HttpClient(handler))
    {
        //QUANDO TESTAR NO SERVIDOR

        client.BaseAddress = new Uri("http://192.111.56.1:1762/");

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpeg"));

        HttpResponseMessage response = await client.GetAsync("api/Nomes/Foto?suspid="+suspid+"&pk="+pk+"");

        if (response.IsSuccessStatusCode)
        {
            var data = response.Content.ReadAsByteArrayAsync().Result;
            var stream = new MemoryStream(data);
            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

            return response;
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            return null;
        }
    }
}

连接到数据库的Web Api:

我隐藏了连接字符串和其他无关紧要的内容。

cmd.InitialLONGFetchSize = -1;
var reader = cmd.ExecuteReader();
byte[] imgBytes = null;

if (reader.Read())
{
    // Fetch the LONG RAW
    OracleBinary imgBinary = reader.GetOracleBinary(0);
    // Get the bytes from the binary obj
    imgBytes = imgBinary.IsNull ? null : imgBinary.Value;

}
connection.Close();
connection.Dispose();

try
{
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new MemoryStream(imgBytes);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

    return result;
}

catch (Exception ex)
{
    return Request.CreateResponse(HttpStatusCode.Gone);
}

0 个答案:

没有答案