簡體   English   中英

在控制台應用程序中使用Api

[英]Consuming Api in Console Application

我正在嘗試使用控制台應用程序使用我的api,但出現異常。 當我嘗試將JSON數據放入模型時,以下是以下例外:

引發的異常:mscorlib.dll中的'Newtonsoft.Json.JsonSerializationException'引發的異常:mscorlib.dll中的'System.AggregateException'引發的異常:ConsoleApplication1.exe中的'Newtonsoft.Json.JsonSerializationException'

我的源代碼:

class Program
{
    public class IndividualModel
    {
        public string PayorCode { get; set; }
        public string Adminlvl { get; set; }
        public string LvlDesc { get; set; }
    }

    static void Main(string[] args)
    {
        HttpClient cons = new HttpClient();
        cons.BaseAddress = new Uri("http://localhost:52505/");
        cons.DefaultRequestHeaders.Accept.Clear();
        cons.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            MyAPIGet(cons).Wait();
        }
        catch (AggregateException e)
        {
            try
            {
                throw e.GetBaseException();
            }
            catch (Exception ea)
            {
                //throw ea.InnerException;
                Console.WriteLine(ea.ToString());
            }
        }
    }

    static async Task MyAPIGet(HttpClient cons)
    {
        using (cons)
        {
            HttpResponseMessage res = await cons.GetAsync("api/PayorPortal/GetPayorUserLevel?payorCode=STARCAR&adminlvl=1");
            res.EnsureSuccessStatusCode();
            if (res.IsSuccessStatusCode)
            {
                IndividualModel tag = await res.Content.ReadAsAsync<IndividualModel>();
                Console.WriteLine("\n");
                Console.WriteLine("---------------------Calling Get Operation------------------------");
                Console.WriteLine("\n");
                Console.WriteLine("tagId tagName tagDescription");
                Console.WriteLine("-----------------------------------------------------------");
                Console.WriteLine("{0}\t{1}\t\t{2}", tag.Adminlvl, tag.LvlDesc, tag.PayorCode);
                Console.ReadLine();
            }
        }
    }
  }
}

這是json數據

“[{\\” PayorCode \\ “:\\” STARCAR \\”,\\ “Adminlvl \\”:\\ “1 \\” \\ “LvlDesc \\”:\\ “管理員\\”},{\\ “PayorCode \\” :\\“ STAR‌CAR \\”,\\“ Adminlvl \\”:\\ ‌“ 2 \\”,\\“ LvlDesc \\”:\\“ Sytemtem Admin \\”},{\\“ PayorCode \\”:\\\\ STARCAR \\ “,\\” Adminlvl \\“:\\” 3 \\“,\\” Lvl‌Desc \\“:\\”系統用戶\\“}]”

當您獲取JSON數據時,請檢查您是獲取單個數據還是列表。 之所以收到此Newtonsoft.Json.JsonSerializationException是因為您無法將JSON數據映射到Model,因為您將其映射到IndividualModel

我的建議是您在GetAsync()之后GetAsync()添加一個斷點,然后檢查它是否為列表。 如果是,則更改此行:

IndividualModel tag = await res.Content.ReadAsAsync<IndividualModel>();

對此:

List<IndividualModel> tag = await res.Content.ReadAsAsync<List<IndividualModel>>();

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM