C#拼接含中间字符串的URL及反序列化DateTime列表求助
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
UritobasePath) for clearer readability. - Added
usingaroundHttpClientto 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

