c# - 使用 OData 在 .NET API 上返回嵌套对象

标签 c# json asp.net-web-api nhibernate odata

我正在开发一个使用 OData 的 .NET API,目前我在将嵌套对象返回给客户端时遇到问题。

一切似乎都在工作,即使我在响应之前在 Controller 上放置了一个断点。我可以看到将与所有信息一起返回的供应商对象已正确填充,但是当我查看客户端收到的 JSON 响应时,它只有原始类型和枚举,作为另一个对象的每个其他属性都没有被序列化到 JSON 结果。

public class Vendor : IEntity
{
    public virtual int Id { get; set; }
    public virtual VendorAddress PrimaryAddress { get; set; }
    public virtual string VendorName { get; set; }
}

public class VendorAddress : IEntity
{
    public virtual int Id { get; set; }
    public virtual Vendor Vendor { get; set; }
    public virtual Address Address { get; set; }

}

 public class Address : IEntity
{
    public virtual int Id { get; set; }   
    public virtual string Line1 { get; set; }
    public virtual string Line2 { get; set; }     
    public virtual string Country { get; set; }
    public virtual string CountryCode { get; set; }
    public virtual string City { get; set; }
    public virtual string County { get; set; }
    public virtual string StateProvince { get; set; }
    public virtual string ZipCode { get; set; }    
}   

 public SingleResult<Vendor> Get([FromODataUri] int key)
{
    var result = _repository.Query<Vendor>().Where(a => a.Id == key);
    return SingleResult.Create(result);
}

基本上我想返回供应商信息,包括 JSON 结果中的 PrimaryAddress/Address 信息,但似乎不知道如何返回。

最佳答案

VendorAddressAddress 是所谓的导航属性。 您可以通过在查询中使用 $expand 来获取它们。 首先在你的Get方法中添加一个[EnableQuery]

[EnableQuery]
public SingleResult<Vendor> Get([FromODataUri] int key)

然后尝试在表单中请求

<serviceUri>/Vendor(1)?$expand=VendorAddress
<serviceUri>/Vendor(1)?$expand=VendorAddress($expand=Address)

你必须添加一行

config.Expand()

在你的

WebApiConfig.Register(HTTPConfiguration config)

方法。

这是一个关于测试服务的示例请求:

http://services.odata.org/TripPinRESTierService/People('russellwhyte')?$expand=BestFriend($expand=Trips)

以及更多信息供引用:http://www.odata.org/odata-services/

希望这对您有所帮助。

关于c# - 使用 OData 在 .NET API 上返回嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43217041/

相关文章:

c# - 如何在后台启动 PhantomJS + Selenium 窗口?

json - GO - 从嵌套的 JSON 对象中获取属性值数组

javascript - 使用 Web API 的纯前端 JavaScript 与使用 ajax 的 MVC View

c# - 从 WPF 客户端访问安全的 Web API

c# - foreach 与 ForEach 使用 yield

c# - 在 C# 5 中将 WPF 事件处理程序声明为 'async' 的意义

c# - 扩展正则语言框架中正则语言的算法复杂度

javascript - 按具有空值的日期排序不起作用 JSON 对象。

python - 将 AttributeError : 'list' object has no attribute 'split' while converting the . 日志文件格式化为 .json 格式

c# - $select 和 $expand 中断 ODataQueryOptions——如何修复?