gpt4 book ai didi

c# - .NET Core Web API 中的 OData 列表/字典序列化

转载 作者:行者123 更新时间:2023-11-30 17:32:16 25 4
gpt4 key购买 nike

我正在使用 .NET Core 2.0.0 和 https://www.nuget.org/packages/microsoft.aspnetcore.odata

到目前为止,这是我的设置。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
...
services.AddOData();
services.AddSingleton<IODataModelManger, ODataModelManager>(DefineEdmModel);
...
}

private ODataModelManager DefineEdmModel(IServiceProvider services)
{
var modelManager = new ODataModelManager();

var builder = new ODataConventionModelBuilder();
builder.EntitySet<TestDTO>(nameof(TestDTO));
builder.EntityType<TestDTO>().HasKey(ai => ai.Id); // the call to HasKey is mandatory
modelManager.AddModel(nameof(Something), builder.GetEdmModel());

return modelManager;
}

public void Configure(...)
{
...
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<TestDTO>("TestDTOs");

app.UseMvc(builder =>
{
builder.MapODataRoute("api", modelBuilder.GetEdmModel());
});
...
}

Controller

[HttpGet("all")]
public async Task<IQueryable<TestDTO>> Get()
{
// plug your entities source (database or whatever)
var test = await TestService.GetTest();

var modelManager = (IODataModelManger)HttpContext.RequestServices.GetService(typeof(IODataModelManger));
var model = modelManager.GetModel(nameof(Something));
var queryContext = new ODataQueryContext(model, typeof(TestDTO), null);
var queryOptions = new ODataQueryOptions(queryContext, HttpContext.Request, Provider);

return queryOptions
.ApplyTo(test, new ODataQuerySettings
{
HandleNullPropagation = HandleNullPropagationOption.True
}, null)
.Cast<TestDTO>();
}

型号

public class TestDTO : BaseEntityDTO
{
[Required]
public Guid Id { get; set; }
public List<CustomerDTO> Customers { get; set; }
public List<string> Tags { get; set; }
[JsonExtensionData]
public IDictionary<string, object> AddProperties { get; set; }
}

问题是使用 services.AddOData(); 我只得到带有属性 Id 的返回结果,没有 services.AddOData(); 我得到所有属性 json格式化。

如何同时序列化 List 属性和 Dictionary 属性?

谢谢。

最佳答案

成功了

var result = queryOptions
.ApplyTo(test, new ODataQuerySettings
{
HandleNullPropagation =
HandleNullPropagationOption.True
}, null)
.Cast<TestDTO>();
return Json(result);

关于c# - .NET Core Web API 中的 OData 列表/字典序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46813876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com