c# - ASP.NET核心: Parse complex struct from URL

标签 c# .net-core

我有 GET API 方法:

[HttpGet]
public List<TripDto> Get([FromQuery]RequestDto req)
{
    // some logic here
}

RequestDto 是一个复杂的对象:

public class RequestDto
{
    public List<SegmentDto> Segments { get; set; } = new List<SegmentDto>();
    public string SessionId { get; set; } 
}

public class SegmentDto
{
    public string Departure { get; set; }
    public string Arrival { get; set; }
    public DateTime Date { get; set; }
}

当我发送请求时:

http://localhost:5000/trips?Segments[0][Departure]=SIP&Segments[0][Arrival]=MOW&Segments[1][Departure]=MOW&Segments[1][Arrival]=SIP&SessionId=s1

在我的 req 变量中,我只看到 session 参数。如何从 GET 请求中解析复杂的列表结构?

最佳答案

1)您不需要初始化仅用于解析的类中的属性

public class RequestDto
{
    public List<SegmentDto> Segments { get; set; }
    public string SessionId { get; set; } 
}

2)对对象使用点表示法(不需要大写名称)

?segments[0].departure=SIP&segments[0].arrival=MOW&...

关于c# - ASP.NET核心: Parse complex struct from URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60532713/

相关文章:

c# - 数组、数组列表还是列表列表?

将谷歌地图集成到 Unity3D 错误的 C# 脚本

c# - MSB4242 : The SDK resolver "Microsoft.DotNet.MSBuildSdkResolver" failed to run. 路径中有非法字符

c# - Identity Server 4 在 IConfigurationDbContext 上没有 SaveChanges 方法

c# - 在 .net core 3.1 类库项目中的构建时设置具有某个值的类私有(private)字符串参数

c# - 内存未释放 .Net 应用程序

c# - Unity 和 WCF 库 : Where to load unity in a wcf library?

c# - 如何反转括号?

c# - 将 ArrayPool 对象提供给 JsonOutputFormatter 构造函数

c# - 在 Parallel.ForEach 中使用 Convert.ChangeType 发生死锁