display an image using web service

r s 21 Reputation points
2021-02-12T15:56:30.613+00:00

I have a web service that returns a URL with a JPG. I want to display the JPG when some one calls the method. I have tried several ways and i am not able to get it to display it.

I have used WebClient and WebRequest. but i am getting errors

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

I don't know if i am doing it right. IS there a different way of doing it without the WebClient and WebRequest

The name of the cs file is Service.asmx.cs

The code is below

[WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public void GetmageBinary()
        {
                //The code returns a URL
                var url = "https://yahoo.comy/profiles/mYImage.jpg?mh=300&mw=300";

// i need to display the image i used webclient

  using (WebClient webClient = new WebClient())
                {
                    byte[] data = webClient.DownloadData(url);

                    using (MemoryStream mem = new MemoryStream(data))
                    {
                        using (var yourImage = System.Drawing.Image.FromStream(mem))
                        {
                            Context.Response.ContentType = "image/jpeg";
                            yourImage.Save(Context.Response.OutputStream, ImageFormat.Jpeg);
                        }
                    }

                }

}
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Alberto Poblacion 1,571 Reputation points
    2021-02-13T12:57:14.06+00:00

    "An existing connection was forcibly closed by the remote host" means that the server refuses to respond to your request. Frequently this is because of a protocol mismatch, or wrong port, or something similar, but it is also possible that the server may simply be closing the connection without responding.
    In the particular case of the url that you are using, I suspect that the problem may be due to using "yahoo.comy" where you probably intended to write "yahoo.com".
    But even if you write yahoo.com, it does not return an image; it returns a login page. Oh, right, it may return an image if you happen to be already logged-in into yahoo. But this will not work from the webservice. Even if your browser is logged-in to yahoo, the webserver will not be logged in, so yahoo will simply return an http login page, which will cause an error when you pass it to Image.FromStream.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.