Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in the below code if status is 200 then it is ok else it redirects to catch method so that i cannot fetch the error detail response on api.

On this line
var response = client.UploadString(webApiUrl, serialisedData);

it redirects to catch method if status of api is not 200.

public object postWebApi(object data, Uri webApiUrl, string id, string password)
       {
           // Create a WebClient to POST the request
           WebClient client = new WebClient();
           client.Encoding = Encoding.UTF8;

           // Set the header so it knows we are sending JSON
           client.Headers[HttpRequestHeader.ContentType] = "application/json";

           // Serialise the data we are sending in to JSON
           string serialisedData = JsonConvert.SerializeObject(data);

           string auth = string.Format("{0}:{1}", id, password);
           string enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
           string cred = string.Format("{0} {1}", "Basic", enc);

           client.Headers[HttpRequestHeader.Authorization] = cred;
           // Make the request
           var response = client.UploadString(webApiUrl, serialisedData);

           // Deserialise the response into a GUID
           return JsonConvert.DeserializeObject(response);
       }


What I have tried:

Please help in case of successful it is fine if the status of response is 400 or other could not read the respnse of api.
Posted
Updated 9-Jul-18 21:22pm
v4
Comments
Kornfeld Eliyahu Peter 10-Jul-18 3:02am    
If there were no exception the only way to go is to look into the response... It is a string that came from the server as-is... Unfortunately there is no standard for that, but it will probably contain a HTTP response code... Do some debugging with different URI and data...

1 solution

var response = string.Empty;
            try
            {
                response = client.UploadString(webApiUrl, serialisedData);
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                }
            }


If exception is found then we will get the response.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900