如何解决OData无法序列化空资源
当OData查询中给定的参数找不到结果时-您将如何处理返回的null值。如果碰巧没有返回结果,或者我只返回null而不进行搜索,就会得到这个异常。
错误:无法序列化空的“资源”
应用程序引发了未处理的异常。 System.Runtime.Serialization.SerializationException:无法序列化 空的“资源”。在 Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSerializer.WriteObjectInline(Object 图,IEdmTypeReference ExpectedType,ODataWriter编写器, ODataSerializerContext writeContext)在 Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSerializer.WriteObject(Object 图,类型类型,ODataMessageWriter messageWriter, ODataSerializerContext writeContext)在 Microsoft.AspNet.OData.Formatter.ODataOutputFormatterHelper.WriteToStream(Type 类型,对象值,IEdmModel模型,ODataVersion版本,Uri baseAddress,MediaTypeHeaderValue contentType,IWebApiUrlHelper internaUrlHelper,IWebApi
我希望它返回一个空结果和一个204代码-但是它返回一个空结果并带有200个代码,并在控制台中引发异常。
这是控制器中的一些示例代码:
[EnableQuery]
[ODataRoute("Topic/{id}")]
public TopicDto? GetTopic(string id)
{
return _dbTableContext.Topic.Find(id);
}
解决方法
请尝试从控制器方法中返回IActionResult
而不是可为空的TopicDto
,因为这会使您在HTTP响应方面更具灵活性。
相同的原则适用于ASP.NET,但返回类型为
IHttpActionResult
。
TopicsController.cs
[ODataRoutePrefix("topics")]
public class TopicsController : ODataController
{
private static readonly TopicViewModel[] _topics = new TopicViewModel[]
{
new TopicViewModel { Id = 1,Title = "Topic A"},new TopicViewModel { Id = 2,Title = "Topic B"},new TopicViewModel { Id = 3,Title = "Topic C"}
};
[EnableQuery]
[ODataRoute("{id}")]
public IActionResult Get(int id)
{
var topic = _topics.FirstOrDefault(x => x.Id == id);
if (topic == null)
{
return NotFound();
}
return Ok(topic);
}
}
使用cURL进行API测试
curl -i "https://localhost:44391/odata/topics(1)"
HTTP/2 200
content-type: application/json; odata.metadata=minimal; odata.streaming=true
server: Microsoft-IIS/10.0
odata-version: 4.0
x-powered-by: ASP.NET
date: Fri,21 Aug 2020 09:28:42 GMT
{"@odata.context":"https://localhost:44391/odata/$metadata#Topics/$entity","Id":1,"Title":"Topic A"}
curl -i "https://localhost:44391/odata/topics(0)"
HTTP/2 404
server: Microsoft-IIS/10.0
x-powered-by: ASP.NET
date: Fri,21 Aug 2020 09:28:54 GMT
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。