C# “C”;未找到该段的资源“;Odata v3中出现错误,状态代码为200

C# “C”;未找到该段的资源“;Odata v3中出现错误,状态代码为200,c#,rest,asp.net-web-api,odata,C#,Rest,Asp.net Web Api,Odata,我试图通过ODataV3从project Online api Url获取数据。问题是,如果找不到资源,我会得到一个状态代码200,请求通过了验证,我的程序因为无效数据而中断 示例URL请求 如果测试不存在,我会得到以下响应 <?xml version="1.0" encoding="utf-8" standalone="yes"?> <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/met

我试图通过ODataV3从project Online api Url获取数据。问题是,如果找不到资源,我会得到一个状态代码200,请求通过了验证,我的程序因为无效数据而中断

示例URL请求

如果测试不存在,我会得到以下响应

<?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>
即使找不到段,状态代码仍返回200

我的示例简化了响应检查

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();

即使状态代码为200,如何检查故障数据?有办法处理吗?

您不能只依赖HTTP状态响应,因为它取决于API的开发方式。仍然可以在消息中发送带有错误响应的HTTP 200状态。因此,最好检查并解析您得到的响应消息。最好两者都做

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();        

如果您想要一种快速的“不干净”方式来解决问题,您可以分析相关错误消息的
response.Content
属性

但是,如果您宁愿用更传统的方式来做,您可以考虑使用而不是手动调用<代码> HTTPcli客< /C> >