You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#拼接含中间字符串的URL及反序列化DateTime列表求助

Fixing Your DateTime List Fetch Code

Let's walk through the two key issues in your code and fix them up:

1. Incorrect URL Concatenation

Your original code treats Id and Date as query parameters (using &=), but based on the target URL structure you shared, Id needs to be embedded directly in the path. The target URL is http://local:8796550/serv/newobj/v678/object/35b724c5424/serv/{Id}/dates — so you just need to append Id straight between your base path and the final /dates segment.

2. Wrong Deserialization Syntax

You tried using dates (your variable name) as the generic type for JsonConvert.DeserializeObject, which won't work. You need to use the actual type List<DateTime> here, and assign the deserialized result to your dates variable to populate it (right now you're returning an empty list).

Corrected Code

public async Task<List<DateTime>> GetDate() 
{ 
    // Target URL structure: http://local:8796550/serv/newobj/v678/object/35b724c5424/serv/{Id}/dates
    List<DateTime> dates = new List<DateTime>(); 
    var id = "xxxxxxxxxxxxxxhola57a"; 
    var basePath = "http://local:8796550/serv/newobj/v678/object/35b724c5424/serv/"; 
    var dateEndpoint = "/dates"; 
    
    using var client = new HttpClient(); // Use 'using' to properly clean up HttpClient
    var fullUrl = $"{basePath}{id}{dateEndpoint}";
    var response = await client.GetAsync(fullUrl); 
    
    // Make sure the request succeeded before parsing the response
    response.EnsureSuccessStatusCode();
    
    string jsonResponse = await response.Content.ReadAsStringAsync(); 
    // Deserialize the JSON to a List<DateTime> and assign to your variable
    dates = JsonConvert.DeserializeObject<List<DateTime>>(jsonResponse); 
    
    return dates; 
}

Quick Extra Tips

  • I renamed some variables (like Uri to basePath) for clearer readability.
  • Added using around HttpClient to ensure it gets disposed properly — this is a best practice to avoid resource leaks.
  • Added response.EnsureSuccessStatusCode(); to catch API errors (like 404 or 500) early, instead of trying to parse invalid JSON.

内容的提问来源于stack exchange,提问作者Pxaml

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:16:46