Odata v3 中的 C# "Resource not found for the segment"错误,状态代码为 200

标签 c# rest asp.net-web-api odata

我正在尝试通过 Odata V3 从项目在线 api Url 获取数据。问题是,如果找不到资源,我会得到一个状态码 200,并且请求通过了验证,我的程序会因为无效数据而中断

示例 URL 请求 https://QASystem/DevQA/_api/ProjectData/test

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

<?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,如何检查错误数据?有办法处理吗?

最佳答案

如果您想快速解决问题,您可以分析 response.Content 属性以获取相关错误消息。

但是,如果您更愿意以更传统的方式进行,您可以考虑使用 Proper OData client而不是手动调用 HttpClient

关于Odata v3 中的 C# "Resource not found for the segment"错误,状态代码为 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55654042/

相关文章:

c# - CMS 6.5 和 7.0 之间的 Sitecore FieldRenderer 输出差异

android - 保护来自 Android 应用程序的 API 调用

java - 多对多关系返回空集合

c# - 我怎样才能看到发送的实际原始请求

c# - 带有 OWIN 的 webapi 中的复杂 JSON Web token 数组

asp.net - 找不到 Http 404

c# - 在 EF 4.0 中,获取 dbcontext 的静态类是否是一种好方法?

c# - RichTextBox 无法显示 Unicode 数学字母数字符号

c# - PInvoke "Attempted to read or write protected memory"

javascript - Mvc WebApi OAuth token 返回