显示来自HttpResponseMessage的图像

时间:2018-10-04 20:31:08

标签: c# asp.net-core

.Net Core Web应用程序正在使用HttpClient检索图像(我认为呢?)。如果浏览器使用这些端点,我认为它将加载图像。我无法检查它,因为端点需要通过标头进行授权,而这在浏览器上是无法完成的。

string endpoint = "somelink";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(endpoint);
client.DefaultRequestHeaders.Add("Accept", "image/jpeg");
client.DefaultRequestHeaders.Add("Authorization", "somekey");

HttpResponseMessage response = await client.GetAsync(endpoint);
Stream receiveStream = await response.Content.ReadAsStreamAsync();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

Console.WriteLine(response);
Console.WriteLine(readStream.ReadToEnd());

我得到的输出为:

enter image description here

在服务器端,我提供了一个字节数组作为内容,因此它应该放在其中的某个地方。我不确定如何使用这些信息来显示图像。

[HttpGet, Route("some link")]
      public HttpResponseMessage GetQRCodeGeneratedForPackagedDrug(string id, bool returnSSLLink = false)
        {
            return GetQRCodeGenerated(id);
        }

    private HttpResponseMessage GetQRCodeGenerated(string drugId)
    {
        Stopwatch totalStopwatch = new Stopwatch();
        totalStopwatch.Start();


        try
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(drugId, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImageBitMap = qrCode.GetGraphic(20);
            ImageConverter converter = new ImageConverter();
            byte[] imgData = (byte[])converter.ConvertTo(qrCodeImageBitMap, typeof(byte[]));
            MemoryStream ms = new MemoryStream(imgData);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(ms);
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
            return this.Request.CreateResponse(System.Net.HttpStatusCode.OK, response);
        }
        catch (Exception ex)
        {
            throw new WebServicesException(ClaimsIdentityHelper.GetServiceCallID(), ex, callContext.CallID);
        }
        finally
        {
            totalStopwatch.Stop();
            Logger.LogResponseTracking(totalStopwatch.ElapsedMilliseconds, ClaimsIdentityHelper.GetServiceCallID(), this.GetType().ToString());
        }
    }

0 个答案:

没有答案