0

Postman returns some response JSON with HTTP status code 406 but my code which is written in C# returns the same HTTP status code error message but from Catch Block.

My Requirement is

The API I am consuming always returns some response JSON either the HTTP status code 200 or 400 or any other. When I test these API from post man it show response JSON but my code returns error when I execute the following line.

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Here is my complete method.

private Dictionary<string, string> HTTPCall(CRMRequestData requestData, out bool isError, out string errorMessage)
        {
            isError = true;
            errorMessage = "HTTPCall - initial error!";
            try
            {
                ServicePointManager.SecurityProtocol = TLS12;

                Dictionary<string, string> responseBag = new Dictionary<string, string>();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestData.Uri);
                
                request.Method = requestData.HttpMethodName;
                request.ContentType = requestData.ContentType;
                request.ContentLength = string.Format("{0}", requestData.Body).Length;
                request.Headers.Add("x-api-key", requestData.APIKey);
                if (requestData.Authorization != null)
                {
                    request.Headers.Add("Authorization", string.Format("JWT {0}",requestData.Authorization));
                }

                if (requestData.HttpMethodName.ToUpper().Equals("POST"))
                {
                    string body = requestData.Body;
                    Byte[] bytes = Encoding.UTF8.GetBytes(body);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(bytes, 0, bytes.Length);
                    }
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();//#Error at this line

                
                string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();

                if (responseData != null && responseData != "")
                {
                    responseBag = ReadResponseJSON(responseData, requestData.CRMMethod, out isError, out errorMessage);
                }

                errorMessage = (!isError) ? "HTTPCall - API executed successfully!" : errorMessage;
                return responseBag;
            }
            catch (Exception ex)
            {
                isError = true;
                errorMessage = string.Format("{0}", ex.Message);
            }
            return null;
        }

*Note: - My code block works fine when API returns the HTTP status code 200 or 201

enter image description here

  • 1
    Using HttpWebRequest, Status Codes above 399 are treated as exceptions. Catch the specific `WebException` instead of a generic Exception: if the Response is not dropped, you can still read its content (in these cases, the exception can contain a non-null Response object and a StatusCode). – Jimi Aug 06 '21 at 07:32
  • Thanks Jimi! I got it. Now, In **WebException** object, I am not able to find out the response content like the postman screenshot. – Praveen Kumar Aug 06 '21 at 07:54
  • 1
    If the Response object is not null and Response.ContentLength is > 0, you have to read it. -- It's probably simpler if you use HttpClient instead (.Net 3.5 ? For real?). – Jimi Aug 06 '21 at 08:06
  • I am using HttpWebRequest in **.NETv3.5**. Response.ContentLength > 100 but I am not able to see response JSON string – Praveen Kumar Aug 09 '21 at 09:22
  • 1
    The content is a Stream, you have to read it. – Jimi Aug 09 '21 at 09:33
  • Thank you very much @Jimi. It is working perfectly when I am reading the content as a stream – Praveen Kumar Aug 09 '21 at 10:16

1 Answers1

0

Try this: What is "406-Not Acceptable Response" in HTTP?

In short: Add Accept header for the response (content type) returned by Service

N.Koshet
  • 31
  • 4