简体   繁体   English

Odata Asp.NET WebApi在实体/ DTO中返回json属性

[英]Odata Asp.NET WebApi return json property in entity/DTO

My Entity QueryFilter has a property, that contains serialized json. 我的实体QueryFilter具有一个属性,其中包含序列化的json。 In QueryFilterDetailDTOController I want to deserialize the JSON, enrich it with some data and return a DTO with the new JSON data. QueryFilterDetailDTOController我想反序列化JSON,用一些数据丰富它,并用新的JSON数据返回DTO。

I want to be able to consume the enriched JSON Object directly as a property of the returned object in javascript (not as string). 我希望能够直接使用丰富的JSON对象作为javascript中返回对象的属性(而不是字符串)。 How can I achieve this? 我该如何实现?

I tried to set the Type of Expression to JObject , but the model builder it throws an exception (because of the recursive Type). 我试图将表达式的类型设置为JObject ,但是模型构建器将引发异常(由于递归类型)。 It this the correct approach, or is there a better way? 这是正确的方法,还是有更好的方法?

DTO DTO

public class QueryFilterDetailDTO
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Context { get; set; }
    public JObject Expression { get; set; }

    public QueryFilterDetailDTO(QueryFilter queryFilter)
    {
        ID = queryFilter.ID;
        Name = queryFilter.Name;
        Description = queryFilter.Description;
        Context = queryFilter.Context;
    }
}

Controller 调节器

public class QueryFilterDetailDTOController : ODataController
{
    private readonly IQueryFilterService _service;

    public QueryFilterDetailDTOController(IQueryFilterService service)
    {
        _service = service;
    }

    [HttpGet]
    [EnableQuery(MaxNodeCount = 1000)]
    public HttpResponseMessage Get([FromODataUri] int key)
    {
        var queryFilter = _service.Find(key);

        var dto = new QueryFilterDetailDTO(queryFilter);
        dto.Expression = JObject.Parse(queryFilter.SerializedFilter);
        dto.Expression["Test"] = 1;

        return Request.CreateResponse(HttpStatusCode.OK, dto);    
    }
}

Create Model 建立模型

private static IEdmModel GetModel()
{
    ODataModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<QueryFilterDetailDTO>("QueryFilterDetailDTO").EntityType.HasKey(dto => dto.ID);
    builder.GetEdmModel();
}

You should be able to use JsonExtensionData for this purpose: JsonExtensionData ,您应该可以使用JsonExtensionData

public class QueryFilterDetailDTO
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Context { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> Expression { get; set; }
}

The extension data holds keys and values for any JSON properties that could not be mapped to c# properties. 扩展数据包含无法映射到c#属性的任何JSON属性的键和值。

For more details see here and here . 有关更多详细信息,请参见此处此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM