2

How can I send Json response by using httpListener class. I have tried some approach but got no luck. I am able to send html and also json as HTML. But not proper json data like webAPI. Here is my piece of code.

 HttpListenerResponse response = context.Response;

            // Construct a response.

            string responseString = //"<HTML><BODY>"+
                ObjToJsonConverter(status);//+ "</BODY></HTML>";

           // Get a response stream and write the response to it.

            byte[] buffer = new byte[] { };

            response.ContentType = "Application/json";

            buffer = Encoding.ASCII.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;

            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);

            output.Close();
            // listener.Stop();
        }
    }

    private static string ObjToJsonConverter(Status obj)
    {
       return "{\"statusText\":\""+obj.StatusText+",\"statusType\":\""+obj.StatusType+"\"}";
    }

which I have tried. I tried to convert my object into jsonstring (above code).But problem of this approach is, response is rendering in chrome but in IE it is downloaded as file. any help would be appreciated.

Rajput
  • 2,597
  • 16
  • 29
  • 1
    You mentioned it is rendering in Chrome. Does that mean that Chrome displays your JSON string and IE isn't? Cause according to [this question](https://stackoverflow.com/questions/2483771/how-can-i-convince-ie-to-simply-display-application-json-rather-than-offer-to-do) IE by default offers to download JSON content instead of displaying. Meaning the issue is probably within the browser, not your code. – RMH Aug 23 '19 at 12:32
  • yes, but Json string is coming like html. but i want something like pure json response from my code, I have tried javascript serializer and stream too, but no luck – Rajput Aug 23 '19 at 12:37
  • there seems to be an issue in `ObjToJsonConverter`. The `obj.StatusText` value isn't closed inside the JSON string, if you fix that it should give out a proper JSON string. If that doesn't fix it, can you provide an example of what response you get and what you are expecting? – RMH Aug 23 '19 at 12:53

0 Answers0