【发布时间】:2022-12-02 00:59:04
【问题描述】:
My code looks like this:
using Newtonsoft.Json;
using System.Net.Http.Headers;
using TestApp.Model.StudentModel;
namespace TestApp.Services
{
public class TodoService
{
public string TodoURL { get; set; } = "https://******.***/api/student";
StudentModel result;
public async Task<List<string>> GetTodoTypesAsync()
{
using (HttpClient client = new HttpClient())
{
// accept respose as json
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
);
// provide token with the request
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", "*****"
)
)
);
HttpResponseMessage response = client.GetAsync(TodoURL).Result;
response.EnsureSuccessStatusCode();
string responseData = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<StudentModel>(responseData);
return result;
}
}
}
}
But I get the following error when I run the app:
Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'TestApp.Model.StudentModel.StudentModel' to 'System.Collections.Generic.List' TestApp C:***\TestApp\Services\TodoService.cs 36 Active
It does not matter if I change
public async Task<List<string>> GetTodoTypesAsync()to
public async Task<List<StudentModel>> GetTodoTypesAsync()And this is a portion of the model StudentModel
namespace TestApp.Model.StudentModel { public class Avatar { public string href { get; set; } } public class StudentModel { public string displayName { get; set; } public string id { get; set; } } }
【问题讨论】:
-
Not related but please do not wrap the
HttpClientinto ausingblock rather reuse it multiple time against the same domain. -
You really should inject that HttpClient.
-
client.GetAsync(TodoURL).Resultoh god, you call that "code that worked"? You're begging for deadlocksandsocket starvation. This is incredibly poor code. -
@Blindy He said he is a beginner. We all learn by failing, don't we? OP: I suggest you make yourself familiar with Stephen Cleary ;D <- That whole blog is liquid gold ...
-
@vaeon 1) change to
Task<List<StudentModel>> GetTodoTypesAsync()2) change toList<StudentModel> result;3) change toresult = JsonConvert.DeserializeObject<List<StudentModel>>(responseData);4)missing a close parenthesisclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue. IMHO - make it work, then optimize later. Your code is def not production ready, so do heed the above cmets aboutHttpClientand def read Stephen Clearly blog