Search code examples
c#imageasp.net-web-apifilestreamwebapi

How can I show image in HttpResponseMessage.Content.Headers.ContentType


I have a method to return an image. As below:

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;
    }
}

How can I show the image in ASP.NET MVC cshtml page?

Postman is ok:

image


Solution

  • I solved it as follows

    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)
                {
                    
                }
            }