如何在 HttpResponseMessage.Content.Headers.ContentType 中显示图像

问题描述 投票:0回答:1

我有一个返回图像的方法。如下:

string fullName = dt.Rows[0]["FileName"].ToString();
string directoryPath = MyFileMultipartFormDataStreamProvider.GetMyFileDirectory();

var myFilePath = Path.Combine(directoryPath, fullName);
using (FileStream fileStream = new FileStream(myFilePath, FileMode.Open))
{
    using (var memoryStream = new MemoryStream())
    {
        fileStream.CopyTo(memoryStream);

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(memoryStream.ToArray());
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

        return result;
    }
}

如何在 ASP.NET MVC cshtml 页面中显示图像?

邮递员还好:

image

c# image asp.net-web-api filestream webapi
1个回答
0
投票

我解决了如下

byte[] mybytearray = null;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(URI);

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

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "");
            try
            {
                Task<HttpResponseMessage> getResponse = client.SendAsync(request);
                HttpResponseMessage response = new HttpResponseMessage();
                response = await getResponse;
                
                if (response.IsSuccessStatusCode)
                {
                    mybytearray = response.Content.ReadAsByteArrayAsync().Result;
                }

                var responseJsonString = await response.Content.ReadAsStringAsync();
                System.Diagnostics.Debug.WriteLine(responseJsonString);
                System.Diagnostics.Debug.WriteLine("GetReportImage ReponseCode: " + response.StatusCode);
            }
            catch (Exception ex)
            {
                
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.