【问题标题】:How to return a JSON result from inside using(){} blockHow to return a JSON result from inside using(){} block
【发布时间】: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 HttpClient into a using block rather reuse it multiple time against the same domain.
  • You really should inject that HttpClient.
  • client.GetAsync(TodoURL).Result oh 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&lt;List&lt;StudentModel&gt;&gt; GetTodoTypesAsync() 2) change to List&lt;StudentModel&gt; result; 3) change to result = JsonConvert.DeserializeObject&lt;List&lt;StudentModel&gt;&gt;(responseData); 4)missing a close parenthesis client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue . IMHO - make it work, then optimize later. Your code is def not production ready, so do heed the above cmets about HttpClient and def read Stephen Clearly blog

标签: c# .net generics blazor


【解决方案1】:

You should supply an example of the JSON but anyways...

You are deserializing your response to StudentModel, implying that your responsedata contains a single StudentModel.

If your responsedata is an Array you should Deserialize it as StudentModel[] or List.

If responsedata contains a single StudentModel then your method needs to return StudentModel not List

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2022-08-12
    • 2022-12-27
    • 2022-12-02
    • 2022-12-26
    • 2022-12-26
    • 2022-12-02
    • 2022-12-26
    • 2022-12-26
    相关资源
    最近更新 更多