Asp.net Web API - How to get JSON response body if status is 400 Bad Request

Cenk 1,021 Reputation points
2022-07-07T10:40:46.323+00:00

Hello Everybody,

I have an ASP.NET Web API rest application. I am calling a 3rd party web service as follows;

 var request = (HttpWebRequest)WebRequest.Create(WebConfigurationManager.AppSettings["PinService"] + url);  
  
            request.ContentType = "application/x-www-form-urlencoded";  
            request.Method = "POST";  
            request.KeepAlive = false;  
            request.Headers.Add("Authorization", "Bearer " + token);  
  
            //Create a list of your parameters  
            var postParams = new List<KeyValuePair<string, string>>(){  
                new KeyValuePair<string, string>("sku", OrderRequest.sku.ToString()) ,  
                new KeyValuePair<string, string>("quantity", OrderRequest.quantity.ToString()),  
                new KeyValuePair<string, string>("pre_order", OrderRequest.pre_order.ToString()),  
                new KeyValuePair<string, string>("price", OrderRequest.price),  
                new KeyValuePair<string, string>("reference_code", OrderRequest.reference_code.ToString())  
            };  
  
            var keyValueContent = postParams;  
            var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);  
            var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();  
  
            using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))  
            {  
                await streamWriter.WriteAsync(urlEncodedString);  
            }  
  
            var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());  
            response = new HttpResponseMessage  
            {  
                StatusCode = httpResponse.StatusCode,  
                Content = new StreamContent(httpResponse.GetResponseStream()),  
            };  
  
            return response;  

For security, I am using a custom exception filter and return Internal Server Error as follows;

 public class CustomExceptionFilter : ExceptionFilterAttribute  
    {  
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();  
  
        public override void OnException(HttpActionExecutedContext actionExecutedContext)  
        {  
            base.OnException(actionExecutedContext);  
  
  
            var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)  
            {  
                ReasonPhrase = "Internal Server Error. Please Contact your Administrator."  
            };  
  
            var timestamp = DateTime.UtcNow;  
  
            //NLOG  
            NLog(Logger, actionExecutedContext.Exception);  
  
            actionExecutedContext.Response = response;  
        }  
  
        private void NLog(Logger logger, Exception message)  
        {  
              
            logger.Error(message);  
        }  
    }  
}  

This web service I am calling returns some sort of error code in the body of JSON response when I get 400 Bad request as status.

{  
    "detail": "This item is available for: Mobile application",  
    "code": "711"  
}  

How can I get this code from the JSON response? I couldn't find this code in the exception. Any help would be great.

Thanks in advance.

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
343 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 66,706 Reputation points
    2022-07-07T20:13:37.37+00:00

    it should throw a web exception. you need to capture the response before the request is closed, so use a local try catch

    try   
    {  
       ....  
    }  
    catch (WebException ex)  
    {  
           var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();  
           dynamic obj = JsonConvert.DeserializeObject(resp);  
           var detail = obj.detail;  
           var code = object.code;  
           ....  
    }  
    
    1 person found this answer helpful.
    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.