C# “Resource not found for the segment” error in Odata v3 with status code 200

Refresh

April 2019

Views

67 time

3

I am trying to get data from project Online api Url through Odata V3. The problem is that if the resource is not found I get a status code 200 and the request passes the validation and my program breaks because of invalid data

Sample URL request https://QASystem/DevQA/_api/ProjectData/test

I get the following response if the test does not exist

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <code></code>
    <message xml:lang="en-US">Resource not found for the segment 'test'></message>
</error>

And the status code returns 200 even though the segment was not found

My sample simplified check for response

HttpResponseMessage response = await ExecutionContext.HttpClient.GetAsync(odataQuery);

// Different checks in real code but here a simple one 
if (response.StatusCode.Equals(HttpStatusCode.ServiceUnavailable) ||
    response.StatusCode.Equals(HttpStatusCode.RequestTimeout) || 
    response.StatusCode.Equals(HttpStatusCode.NotFound)
    // Log error Here 
    throw new TransientFaultException();

How can I check for the faulty data even if the status code is 200? Is there a way to handle it?

2 answers

0

If you want a quick'n'dirty way to get around the issue, you can analyze response.Content property for the relevant error messages.

However, if you would rather do it in a more conventional way, you may consider using Proper OData client instead of manually calling HttpClient.

0

You can not just rely on HTTP status response, as it depends on how the API is developed. One can still send HTTP 200 status with error response in message. So it is better to check and parse the response message you are getting. Better to do the both.

HttpResponseMessage response = await ExecutionContext.HttpClient.GetAsync(odataQuery);

// Different checks in real code but here a simple one 
if (response.StatusCode.Equals(HttpStatusCode.ServiceUnavailable) || 
    response.StatusCode.Equals(HttpStatusCode.RequestTimeout) || 
    response.StatusCode.Equals(HttpStatusCode.NotFound)
    if (response.Content.ToString().Contains("error") ||
        response.Content.ToString().Contains("Resource not found"))
        // Log error Here 
        throw new TransientFaultException();